mrbone / mrbone.github.io

0 stars 0 forks source link

ES6 module export directly #88

Closed mrbone closed 6 years ago

mrbone commented 6 years ago

Export Imported Module

es6 模块的导出方法有如下几种:

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 …;
export { default } from …;

注意 export { default } from …; 这一行的 default 是指将 ... 模块的 default 值作为当前模块的 default 值导出。当前模块只能有一个 default 导出。

export { default } from 'a';
export { default } from 'b'; //会抛错

上述代码会编译报错,因为一个模块只能有一个 default 导出值.
这里有一个坑是,如果有一个 中间模块 帮助我们做一些其他模块的整理一并导出的话,其他模块的 default 值会被过滤掉。

//a.js
const a = 'a';

export default a;

export const aa = 'aa';

//b.js
const b = 'b';

export default b;

//middleware.js
export * from './a';
export * from './b';

当我们 import middleware 模块的时候会得到:

import * as middleware from './middleware';
console.log(middleware); // {aa: 'aa'}

所以如果我们得到所有模块的值的话需要变更下 middleware 导出方式。

export {default as a, aa} from './a';
export {default as b} from './b';

我们必须显示的声明 想要导出 的模块的值对应 当前模块 的导出值是什么。