### 語法
~~~
export { name1, name2, …, nameN };
export { variable1 as name1, variable2 as name2, …, nameN };
export let name1, name2, …, nameN; // also var
export let name1 = …, name2 = …, …, nameN; // also var, const
export function FunctionName() {...}
export class ClassName {...}
export default expression;
export default function (…) { … } // also class, function*
export default function name1(…) { … } // also class, function*
export { name1 as default, … };
export * from …;
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;
~~~
nameN導出的標識符(用來被其他腳本的import導入)
### 命名導出
~~~js
// exports a function declared earlier
export { myFunction };
// exports a constant
export const foo = Math.sqrt(2);
~~~
### 默認導出(函數)
~~~js
export default function() {}
~~~
### 默認導出(類)
~~~js
export default class {}
~~~
命名導出對導出多個值很有用。在導入期間,必須使用相應對象的相同名稱。
但是,可以使用任何名稱導入默認導出,例如:
~~~
export default k = 12; // in file test.js
import m from './test' // note that we got the freedom to use import m instead of import k, because k was default export
console.log(m); // will log 12
~~~
**只能有一個默認的導出**
如果需要導出默認值,請使用下列代碼:
~~~html
import mod from "mod";
export default mod;
~~~
### 示例:
標準導出
~~~js
// module "my-module.js"
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
export { cube,foo };
~~~
其他腳本引用
~~~js
import { cube, foo } from 'my-module.js';
console.log(cube(3)); // 27
console.log(foo); // 4.555806215962888
~~~
默認導出
如果我們要導出一個值或模塊中的返回值,就可以使用默認導出:
~~~js
// module "my-module.js"
export default function cube(x) {
return x * x * x;
}
~~~
然后,在另一個腳本中,可以直接導入默認導出:
~~~js
// module "my-module.js"
import cube from 'my-module';
console.log(cube(3)); // 27?????
~~~
### 模塊重定向
如果我們要從另一個模塊(有效地創建“重定向”)中導出默認值(default)和 星標(\*):
~~~
// module "redirect-module.js"
export {default} from './other-module';
export * from './other-module';
~~~