JS中export怎么用()

一、export 用法 【JS中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 myFunction let myVariable = ...; // assign something useful to myVariable export {myFunction, myVariable};

// childModule2.js 中 let myClass = ...; // assign something useful to myClass export 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, const export let name1 = …, name2 = …, …, nameN; // also var, const export 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 export export * as name1 from …; // Draft ECMAScript? 2O21 export { name1, name2, …, nameN } from …; export { import1 as name1, import2 as name2, …, nameN } from …; export { default } from …;

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

    推荐阅读