Stories

Detail Return Return

CommonJS的兩種導出方式 - Stories Detail

知道的朋友應該知道,CommonJS有兩種導出方式,如下所示:

// module1.js
const name1 = 'Ben';
const name2 = 'Lisa'

// 導出方式1
module.exports = {
  name1,
  name2,
};

// 導出方式2
exports.name1 = name1;
exports.name2 = name2;

差異

那麼上面這兩種導出方式有什麼差異呢?
先説結論,從導出的結果來看,沒有差異。

import module1 from './module1.js'
// 無論module1.js中使用的哪種方式導出,這裏得到的module1都是一樣的結構。

console.log(module1)
// { name1, name2 }

為什麼沒有差異

至於為什麼兩者沒有差異,原因也很簡單。
module.exportsexports是相等的,因為exports就是引用自module.exports

const name = 'Ben';

// 這兩個寫法是等價的
exports.name = name
module.exports = { name }

看下圖,給exports添加一個name屬性,也就是相當於給module.exports添加了一個屬性,反之亦然。
image.png

注意

避免意外切斷引用關係

不要使用下面的導出方式,還記得exports是引用自module.exports嗎,下面這種寫法,給exports重新賦值,也就切斷了exportsmodule.exports的引用關係,所以也就無法導出了。

const name = 'Ben';
exports = {
    name
}

避免同時使用兩種方式

const name1 = 'Ben';
const name2 = 'Lisa'

// 導出方式1
module.exports = {
  name1,
};

// 導出方式2
exports.name2 = name2;

上面同時存在兩種導出方式的情況,會導致導出方式2會被忽略。

還記得他們的引用關係嗎?導出方式1將引用關係切斷了,所以就會導致導出方式2失敗。

user avatar dingtongya Avatar smalike Avatar zaoying Avatar razyliang Avatar Dream-new Avatar shuirong1997 Avatar aresn Avatar zhaodawan Avatar shuyuanutil Avatar best-doraemon Avatar johanazhu Avatar esunr Avatar
Favorites 47 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.