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

解构赋值

有如下 config 对象

const config = {
  host: 'localhost',
  port: 80
}

要获取其中的 host 属性

let { host } = config

拆分成模块

以上两段代码,放到同一个文件当中不会有什么问题,但在一个项目中,config 对象多处会用到,现在把 config 对象放到 config.js 文件当中。

// 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

上面这段代码也不会有问题。但在 import 语句当中解构赋值呢?

// app.js
import { host } from './config'

console.log(host) // => undefined

问题所在

import { host } from './config'

这句代码,语法上是没什么问题的,之前用 antd-init 创建的项目,在项目中使用下面的代码是没问题的。奇怪的是我在之后用 vue-cli 和 create-react-app 创建的项目中使用下面的代码都不能正确获取到 host

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

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

babel 对 export default 的处理

我用 Google 搜 'es6 import 解构失败',找到了下面的这篇文章:ES6的模块导入与变量解构的注意事项。原来经过 webpack 和 babel 的转换

export default {
  host: 'localhost',
  port: 80
}

变成了

module.exports.default = {
  host: 'localhost',
  port: 80
}

所以取不到 host 的值是正常的。那为什么 antd-init 建立的项目有可以获取到呢?

解决

再次 Google,搜到了GitHub上的讨论 。import 语句中的"解构赋值"并不是解构赋值,而是 named imports,语法上和解构赋值很像,但还是有所差别,比如下面的例子。

import { host as hostName } from './config' // 解构赋值中不能用 as

let obj = {
  a: {
    b: 'hello',
  }
}

let {a: {b}} = obj // import 语句中不能这样子写
console.log(b) // => helllo

这种写法本来是不正确的,但 babel 6之前可以允许这样子的写法,babel 6之后就不能了。

// a.js
import { foo, bar } from "./b"
// b.js
export default {
  foo: "foo",
  bar: "bar"
}

所以还是在import 语句中多加一行

import b from './b'
let { foo, bar } = b

或者

// a.js
import { foo, bar } from "./b"
// b.js
let foo =  "foo"
let bar = "bar"
export { foo, bar }

或者

// a.js
import { foo, bar } from "./b"
// b.js
export let foo =  "foo"
export let bar = "bar"

antd-init 使用了 babel-plugin-add-module-exports,所以 export default 也没问题。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容