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: } = 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 也沒問題。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容