[es6] import, export, default cheatsheet
有四种类型的导出:
1、命名导出(每个模块可以有多个)
2、默认导出(每个模块一个)
3、混合命名和默认导出
4、循环依赖
1. Name 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';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
or
//------ main.js ------
import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
2. Default exports (one per module)
//------ myFunc.js ------
export default function () { ... };
//------ main1.js ------
import myFunc from 'myFunc';
myFunc();
3. Mixed named & default exports
//------ underscore.js ------
export default function (obj) {
...
};
export function each(obj, iterator, context) {
...
}
export { each as forEach };
//------ main.js ------
import _, { each } from 'underscore';
...
4. Cyclical Dependencies
// lib.js
import Main from 'main';
var lib = {message: "This Is A Lib"};
export { lib as Lib };
// main.js
import { Lib } from 'lib';
export default class Main {
// ....
}
参考:http://2ality.com/2014/09/es6-modules-final.html