1. 程式人生 > 實用技巧 >module.exports 和 exports,export 和export default的區別

module.exports 和 exports,export 和export default的區別

Node應用由模組組成,採用CommonJS模組規範。

根據這個規範,每個檔案就是一個模組,有自己的作用域。在一個檔案裡面定義的變數、函式、類,都是私有的,對其他檔案不可見。

CommonJS規範規定,每個模組內部,module變數代表當前模組。這個變數是一個物件,它的exports屬性(即module.exports)是對外的介面。載入某個模組,其實是載入該模組的module.exports屬性。

var x = 5;
var addX = function (value) {
  return value + x;
};
module.exports.x = x;
module.exports.addX = addX;

上面程式碼通過module.exports輸出變數x和函式addX。

require方法用於載入模組。

var example = require('./example.js'); console.log(example.x); // 5 console.log(example.addX(1)); // 6

exports 與 module.exports

優先使用 module.exports

為了方便,Node為每個模組提供一個exports變數,指向module.exports。這等同在每個模組頭部,有一行這樣的命令。

var exports = module.exports;

於是我們可以直接在 exports 物件上新增方法,表示對外輸出的介面,如同在module.exports上新增一樣。

注意,因為Node 模組是通過 module.exports 匯出的,如果直接將exports變數指向一個值,就切斷了exports與module.exports的聯絡,導致意外發生:

// a.js
exports = function a() {};

// b.js
const a = require('./a.js') // a 是一個空物件

ES6模組規範

不同於CommonJS,ES6使用 export 和 import 來匯出、匯入模組。

// profile.js

var firstName = 'Michael'; var lastName = 'Jackson'; var year = 1958; export {firstName, lastName, year};

需要特別注意的是,export命令規定的是對外的介面,必須與模組內部的變數建立一一對應關係。

// 寫法一
export var m = 1;

// 寫法二
var m = 1;
export {m};

// 寫法三
var n = 1;
export {n as m};

export default 命令

使用export default命令,為模組指定預設輸出。

// export-default.js
export default function () {
  console.log('foo');
}