ES6 export default 和 import語句中的解構(gòu)賦值

解構(gòu)賦值

有如下 config 對(duì)象

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

要獲取其中的 host 屬性

let { host } = config

拆分成模塊

以上兩段代碼,放到同一個(gè)文件當(dāng)中不會(huì)有什么問題,但在一個(gè)項(xiàng)目中,config 對(duì)象多處會(huì)用到,現(xiàn)在把 config 對(duì)象放到 config.js 文件當(dāng)中。

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

上面這段代碼也不會(huì)有問題。但在 import 語句當(dāng)中解構(gòu)賦值呢?

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

console.log(host) // => undefined

問題所在

import { host } from './config'

這句代碼,語法上是沒什么問題的,之前用 antd-init 創(chuàng)建的項(xiàng)目,在項(xiàng)目中使用下面的代碼是沒問題的。奇怪的是我在之后用 vue-cli 和 create-react-app 創(chuàng)建的項(xiàng)目中使用下面的代碼都不能正確獲取到 host

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

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

babel 對(duì) export default 的處理

我用 Google 搜 'es6 import 解構(gòu)失敗',找到了下面的這篇文章:ES6的模塊導(dǎo)入與變量解構(gòu)的注意事項(xiàng)。原來經(jīng)過 webpack 和 babel 的轉(zhuǎn)換

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

變成了

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

所以取不到 host 的值是正常的。那為什么 antd-init 建立的項(xiàng)目有可以獲取到呢?

解決

再次 Google,搜到了GitHub上的討論 。import 語句中的"解構(gòu)賦值"并不是解構(gòu)賦值,而是 named imports,語法上和解構(gòu)賦值很像,但還是有所差別,比如下面的例子。

import { host as hostName } from './config' // 解構(gòu)賦值中不能用 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 也沒問題。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容