標籤:last 其他 檔案 OLE class 輸出 es6 default export
首先我們要明白一個前提,CommonJS模組規範和ES6模組規範完全是兩種不同的概念。
CommonJS模組規範
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); // 5console.log(example.addX(1)); // 6
exports 與 module.exports
為了方便,Node為每個模組提供一個exports變數,指向module.exports。這等同在每個模組頭部,有一行這樣的命令。
var exports = module.exports;
於是我們可以直接在 exports 對象上添加方法,表示對外輸出的介面,如同在module.exports上添加一樣。注意,不能直接將exports變數指向一個值,因為這樣等於切斷了exports與module.exports的聯絡。
ES6模組規範
不同於CommonJS,ES6使用 export 和 import 來匯出、匯入模組。
// profile.jsvar 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.jsexport default function () { console.log(‘foo‘);}
ES6的export與Nodejs的module.exports比較