[转] ES6 import/export:模块导入导出方式

时间:2021-01-31 23:19:22
export导出语法

// default exports
export default 42;
export default {};
export default [];
export default foo;
export default function () {}
export default class {}
export default function foo () {}
export default class foo {}

// variables exports
export var foo = 1;
export var foo = function () {};
export var bar; // lazy initialization
export let foo = 2;
export let bar; // lazy initialization
export const foo = 3;
export function foo () {}
export class foo {}

// named exports
export {foo};
export {foo, bar};
export {foo as bar};
export {foo as default};
export {foo as default, bar};

// exports from
export * from "foo";
export {foo} from "foo";
export {foo, bar} from "foo";
export {foo as bar} from "foo";
export {foo as default} from "foo";
export {foo as default, bar} from "foo";
export {default} from "foo";
export {default as foo} from "foo";

示例:

1、export {function};
  导出一个函数
2、export const foo = 2;
  导出一个常量
3、export default myFunctionClass;
  默认导出,每个模块只有一个默认导出,导出的可以是一个函数,一个对象,一个类

import导入语法

// default imports
import foo from "foo";
import {default as foo} from "foo";

// named imports
import {bar} from "foo";
import {bar, baz} from "foo";
import {bar as baz} from "foo";
import {bar as baz, xyz} from "foo";

// glob imports
import * as foo from "foo";

// mixing imports
import foo, {baz as xyz} from "foo";
import * as bar, {baz as xyz} from "foo";
import foo, * as bar, {baz as xyz} from "foo";

示例

1、import name from 'my-module.js' ;
  导出整个模块到当前作用域,name作为接收该模块的对象名称
  
2、import {moduleName} from 'my-module.js';
   导出模块中的单个成员moduleName

3、import {moduleName1,moduleName2} from 'my-module';
  导出模块中的多个成员moduleName1、moduleName2
  
4、import {moduleName as moduleAlias} from 'my-module';

5、import myDefault,{moduleName1,moduleName2} from 'my-module';
  myDefault为my-module.js文件default导出项

注意事项

导入语句只能作为模块顶层的语句出现,不能出现在 function 里面或是 if 里面
if(Math.random()>0.5){
  import './module1.js'; // SyntaxError: Unexpected keyword 'import'
}
const import2 = (import './main2.js'); // SyntaxError
try{
  import './module3.js'; // SyntaxError: Unexpected keyword 'import'
}catch(err){
  console.error(err);
}
const moduleNumber = 4;

import module4 from `module${moduleNumber}`; // SyntaxError: Unexpected token

import 语句会被提升到文件顶部执行,也就是说在模块初始化的时候所有的 import 都必须已经导入完成
import './module1.js';
alert('code1');

import module2 from './module2.js';
alert('code2');

import module3 from './module3.js';

// 执行结果
module1
module2
module3


import 的模块名只能是字符串常量,导入的值也是不可变对象;比如说你不能 import { a } from ‘./a’ 然后给 a 赋值个其他什么东西