本文參考/整理/節錄自2ality blog
兩種export方法:named exports (several per module) and default exports (one per module)
named export
一個module(.js file)可有多個named exports
//------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } //------ main.js ------ import { square, diag } from 'lib'; //square和diag必須與lib export出來的name一致 console.log(square(11)); // 121 console.log(diag(4, 3)); // 5 //引入全部的寫法也適用 //------ main.js ------ import * as lib from 'lib'; console.log(lib.square(11)); // 121 console.log(lib.diag(4, 3)); // 5
default export
一個module(.js file)只能有一個default export
//------ myFunc.js ------ export default function () { ... }; //------ main1.js ------ import myFunc from 'myFunc'; //這裡的myFunc可以自己亂取 myFunc();
實際上default export就是一個名為default的named export
所以下面兩種import/export code等效
//等效import import { default as foo } from 'lib'; import foo from 'lib'; //等效export //------ module1.js ------ export default 123; //------ module2.js ------ const D = 123; export { D as default };
CommonJS的寫法
//------ lib.js ------ var sqrt = Math.sqrt; function square(x) { return x * x; } function diag(x, y) { return sqrt(square(x) + square(y)); } module.exports = { //關鍵! sqrt: sqrt, square: square, diag: diag, }; //------ main.js ------ //require是關鍵! var square = require('lib').square; var diag = require('lib').diag; console.log(square(11)); // 121 console.log(diag(4, 3)); // 5
來看看underscore.js如何同時寫named export和default export (CommonJS)
//------ underscore.js ------ var _ = function (obj) { //用於default export ... }; var each = _.each = _.forEach = function (obj, iterator, context) { //用於named export ... }; module.exports = _; //------ main.js ------ var _ = require('underscore'); var each = _.each; ...
上面的CommonJS module寫法(nested)等同於以下的ES6 module寫法(flat)
//------ underscore.js ------ export default function (obj) { ... }; export function each(obj, iterator, context) { ... } export { each as forEach }; //------ main.js ------ import _, { each } from 'underscore'; ...
underscore.js這種包法很常見~
將library包成單一function,額外的附加功能/服務則以此單一function的property實踐
結論:建議用ES6 module規範來寫import和export,瀏覽器不支援的問題靠babel解決