详解ES6 export default 和 import语句中的解构赋值

878 阅读1分钟

存在一个疑问

- 在config文件中导出一个对象

// config.js
export default {
 host: 'localhost',
 port: 80
}

- 在在 app.js 中 import config.js

// app.js
import config from './config'
 
let { host } = config
console.log(host) // => localhost
console.log(config.host) // => localhost

上面的写法的没有问题的,但是下面的写法是undefined
// app.js
import { host } from './config'
console.log(host) // => undefined

问题的探索

import { host } from './config'

之前用 antd-init 创建的项目,在项目中使用下面的代码是没问题的。奇怪的是我在之后用 vue-cli 和 create-react-app 创建的项目中使用下面的代码都不能正确获取到 host。而 antd-init 使用了babel-plugin-add-module-exports,所以 export default 也没问题

原因

原来经过 webpack 和 babel 的转换

解决

***方式一***
// a.js
import { foo, bar } from "./b"
// b.js
export default {
 foo: "foo",
 bar: "bar"
}
import b from './b'
let { foo, bar } = b  //多加一行



***方式二***
// b.js
let foo = "foo"
let bar = "bar"
export { foo, bar }   //通过export导出
// a.js
import { foo, bar } from "./b"