[轉] ES6 import/export:模塊導入導出方式

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";

示例:

一、export {function};
  導出一個函數
二、export const foo = 2;
  導出一個常量
三、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";

示例

一、import name from 'my-module.js' ;
  導出整個模塊到當前做用域,name做爲接收該模塊的對象名稱
  
二、import {moduleName} from 'my-module.js';
   導出模塊中的單個成員moduleName

三、import {moduleName1,moduleName2} from 'my-module';
  導出模塊中的多個成員moduleName一、moduleName2
  
四、import {moduleName as moduleAlias} from 'my-module';

五、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 賦值個其餘什麼東西
相關文章
相關標籤/搜索