ES 6 import/export:モジュール導入導出方式

9293 ワード

選択してからhttps://zhuanlan.zhihu.com/p/26231889 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";
例:
1export {function};
        
2export const foo = 2;
        
3export 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";
1import name from 'my-module.js' ;
              ,name            
  
2import {moduleName} from 'my-module.js';
             moduleName

3import {moduleName1,moduleName2} from 'my-module';
            moduleName1、moduleName2
  
4import {moduleName as moduleAlias} from 'my-module';

5import 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
code1
code2
importのモジュール名は文字列定数だけで、導入された値も可変オブジェクトではありません.例えば、あなたはimport{a}from'./a'ができなくて、aに他の何かを与えます.