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 賦值個其他什么東西