ES模块(ECMAScript Modules, ESM)是 JavaScript 提供的一种模块化机制,它允许你在不同的文件之间共享代码。ES模块采用 import
和 export
语法来处理模块导入和导出。
基本写法
1. 导出(export
)
你可以导出一个变量、函数、类、对象等,供其他模块使用。
1.1 导出单个内容
将一个函数或变量导出:
// utils.js
const greeting = 'Hello, world!';
export function sayHello() {
console.log(greeting);
}
1.2 导出多个内容
一次导出多个变量、函数等:
// utils.js
export const greeting = 'Hello, world!';
export function sayHello() {
console.log(greeting);
}
1.3 默认导出(default
)
你可以指定一个模块的默认导出,使得导入时可以使用任何名称:
// utils.js
const greeting = 'Hello, world!';
export default function sayHello() {
console.log(greeting);
}
2. 导入(import
)
在另一个模块中使用 import
语句来引入已经导出的内容。
2.1 导入单个内容
从另一个模块导入一个特定的导出:
// app.js
import { sayHello } from './utils.js';
sayHello(); // 输出: Hello, world!
2.2 导入多个内容
从一个模块导入多个导出:
// app.js
import { greeting, sayHello } from './utils.js';
console.log(greeting); // 输出: Hello, world!
sayHello(); // 输出: Hello, world!
2.3 导入默认导出
导入默认导出的内容,通常可以起一个自定义名称:
// app.js
import sayHello from './utils.js';
sayHello(); // 输出: Hello, world!
2.4 导入所有导出
如果模块中有很多导出,可以使用 * as
导入所有内容:
// app.js
import * as utils from './utils.js';
console.log(utils.greeting); // 输出: Hello, world!
utils.sayHello(); // 输出: Hello, world!
3. 使用模块的路径
- 对于本地模块,路径需要以
./
或../
开头。 - 如果是从
node_modules
导入的包,则不需要路径。
例如:
import express from 'express'; // 从 node_modules 导入
import { sayHello } from './utils.js'; // 本地模块
4. 模块加载方式
- 同步加载:ES模块是静态的,在编译时确定模块的导入和导出关系。它们会在加载时异步加载,但使用时是同步的。
完整示例
假设你有两个文件:utils.js
和 app.js
。
utils.js(定义模块内容):
// utils.js
export const greeting = 'Hello, world!';
export function sayHello() {
console.log(greeting);
}
export default function greetPerson(name) {
console.log(`Hello, ${name}!`);
}
app.js(导入并使用模块):
// app.js
import greetPerson, { greeting, sayHello } from './utils.js';
console.log(greeting); // 输出: Hello, world!
sayHello(); // 输出: Hello, world!
greetPerson('Alice'); // 输出: Hello, Alice!
5. 配置 package.json
确保你的项目的 package.json
配置了 "type": "module"
,否则 Node.js 会将 .js
文件当作 CommonJS 处理。
{
"type": "module"
}
总结
export
用于在模块中导出函数、变量或对象。import
用于在其他模块中导入已经导出的内容。- 可以通过 默认导出(
export default
)来指定一个模块的主要内容。 - ES模块提供了更好的静态分析、支持异步加载和更简洁的语法,适用于现代 JavaScript 开发。
发表回复
要发表评论,您必须先登录。