一、export 用法

有两种不同的导出形式:命名导出和默认导出。命名导出能够导出多个接口,而默认导出,只能导出一个。

1、命名导出:
  • 导入时,必须应用导出接口的名字。

    // 导出当时定义的个性export { myFunction,myVariable };// 导出单个个性(能够导出var,let,const,function,class)export let myVariable = Math.sqrt(2);export function myFunction() { ... };
2、默认导出:
  • 导入时,能够应用任意名字来示意导出接口。

    // 导出当时定义的个性作为默认值export { myFunction as default };// 导出单个个性作为默认值export default function () { ... }export default class { .. }// 每个导出都笼罩前一个导出
  • 如果咱们要导出一个值或失去模块中的返回值,就能够应用默认导出

    // module "my-module.js"export default function cube(x) {  return x * x * x;}
    import cube from './my-module.js';console.log(cube(3)); // 27

二、模块重定向

举个例子,如果咱们有如下层次结构:

  • childModule1.js: 导出 myFunctionmyVariable
  • childModule2.js: 导出 myClass
  • parentModule.js: 作为聚合器(不做其余事件)
  • 顶层模块:调用 parentModule.js 的导出项
// childModule1.js 中let myFunction = ...; // assign something useful to myFunctionlet myVariable = ...; // assign something useful to myVariableexport {myFunction, myVariable};
// childModule2.js 中let myClass = ...; // assign something useful to myClassexport myClass;
// parentModule.js 中// 仅仅聚合 childModule1 和 childModule2 中的导出// 以从新导出他们export { myFunction, myVariable } from 'childModule1.js';export { myClass } from 'childModule2.js';
// 顶层模块中// 咱们能够从单个模块调用所有导出,因为 parentModule 当时// 曾经将他们“收集”/“打包”到一起import { myFunction, myVariable, myClass } from 'parentModule.js'

三、语法补充
// 导出单个个性export let name1, name2, …, nameN; // also var, constexport let name1 = …, name2 = …, …, nameN; // also var, constexport function FunctionName(){...}export class ClassName {...}// 导出列表export { name1, name2, …, nameN };// 重命名导出export { variable1 as name1, variable2 as name2, …, nameN };// 解构导出并重命名export const { name1, name2: bar } = o;// 默认导出export default expression;export default function (…) { … } // also class, function*export default function name1(…) { … } // also class, function*export { name1 as default, … };// 导出模块合集export * from …; // does not set the default exportexport * as name1 from …; // Draft ECMAScript® 2O21export { name1, name2, …, nameN } from …;export { import1 as name1, import2 as name2, …, nameN } from …;export { default } from …;

四、参考文档
  • JS中export怎么用?