ES6 Module 的语法(十二)

avatar
作者
猴君
阅读量:1

ES6(ECMAScript 2015)引入了模块(Modules)的概念,使得JavaScript代码可以更容易地组织和复用。

1. export 关键字

命名导出 (Named Exports)
你可以使用 export 关键字导出多个变量、函数或类。

// module.js export const name = 'John'; export function greet() {   console.log('Hello, ' + name); } export class Person {   constructor(name) {     this.name = name;   } }  

默认导出 (Default Export)
每个模块只能有一个默认导出,用 export default 来实现。

// module.js export default function() {   console.log('This is the default export'); }  

2. import 关键字

导入命名导出 (Importing Named Exports)
使用 import 关键字可以导入其他模块的命名导出。

// main.js import { name, greet, Person } from './module.js';  console.log(name); // John greet(); // Hello, John const person = new Person('Jane'); console.log(person.name); // Jane  

导入默认导出 (Importing Default Export)
导入默认导出时,不需要使用大括号。

// main.js import myFunction from './module.js';  myFunction(); // This is the default export  

导入所有导出 (Importing All Exports)
可以使用 * as 语法导入一个模块的所有导出,并将其绑定到一个对象上。

// main.js import * as myModule from './module.js';  console.log(myModule.name); // John myModule.greet(); // Hello, John const person = new myModule.Person('Jane'); console.log(person.name); // Jane  

3. 重新导出 (Re-Exporting)

可以从一个模块中重新导出另一个模块的导出。

// module1.js export const a = 1; export const b = 2;  // module2.js export { a, b } from './module1.js'; export const c = 3;  // main.js import { a, b, c } from './module2.js';  console.log(a, b, c); // 1 2 3  

4. 动态导入 (Dynamic Import)

ES2020引入了动态导入,使用 import() 函数可以在运行时按需加载模块。

// main.js async function loadModule() {   const module = await import('./module.js');   module.greet(); // Hello, John }  loadModule();  

5. 具有副作用的模块 (Modules with Side Effects)

一些模块在导入时会执行一些代码,这些模块被称为具有副作用的模块。

// sideEffectModule.js console.log('Module loaded');  // main.js import './sideEffectModule.js'; // Module loaded  

6. export 和 import 的高级用法

导出和导入时重命名
可以在导出和导入时使用 as 关键字进行重命名。

// module.js const name = 'John'; function greet() {   console.log('Hello, ' + name); } export { name as userName, greet as sayHello };  // main.js import { userName, sayHello } from './module.js';  console.log(userName); // John sayHello(); // Hello, John  

导出时使用默认导出和命名导出

// module.js export const name = 'John'; export default function() {   console.log('This is the default export'); }  // main.js import defaultFunction, { name } from './module.js';  console.log(name); // John defaultFunction(); // This is the default export  

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!