介绍


ECMAScript 模块是来打包 JavaScript 代码以供重用的官方标准格式。 模块使用各种 importexport 语句定义。

以下是 ES 模块导出函数的示例:

// addTwo.mjs
function addTwo(num) {
  return num + 2;
}

export { addTwo };

以下是 ES 模块从 addTwo.mjs 导入函数的示例:

// app.mjs
import { addTwo } from './addTwo.mjs';

// 打印: 6
console.log(addTwo(4));

Node.js 完全支持当前指定的 ECMAScript 模块,并且提供它们与其原始模块格式 CommonJS 之间的互操作性。

ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements.

The following example of an ES module exports a function:

// addTwo.mjs
function addTwo(num) {
  return num + 2;
}

export { addTwo };

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 fully supports ECMAScript modules as they are currently specified and provides interoperability between them and its original module format, CommonJS.