介绍
【Introduction】
ECMAScript 模块用于打包可重用的 JavaScript 代码。模块是使用各种 import 和 export 语句定义的。
【ECMAScript modules are the official standard format to package JavaScript
code for reuse. Modules are defined using a variety of import and
export statements.】
以下是 ES 模块导出函数的示例:
【The following example of an ES module exports a function:】
// addTwo.mjs
function addTwo(num) {
return num + 2;
}
export { addTwo }; 下面是一个 ES 模块的示例,它从 addTwo.mjs 导入函数:
【The following example of an ES module imports the function from addTwo.mjs:】
// app.mjs
import { addTwo } from './addTwo.mjs';
// Prints: 6
console.log(addTwo(4)); Node.js 完全支持当前规范的 ECMAScript 模块,并提供它们与其原始模块格式之间的互操作性,CommonJS。
【Node.js fully supports ECMAScript modules as they are currently specified and provides interoperability between them and its original module format, CommonJS.】