启用


¥Enabling

Node.js 有两个模块系统:CommonJS 模块和 ECMAScript 模块。

¥Node.js has two module systems: CommonJS modules and ECMAScript modules.

作者可以通过 .mjs 文件扩展名、值为 "module"package.json "type" 字段、值为 "module"--input-type 标志或值为 "module"--experimental-default-type 标志,告诉 Node.js 将 JavaScript 解释为 ES 模块。这些是打算作为 ES 模块运行的代码的显式标记。

¥Authors can tell Node.js to interpret JavaScript as an ES module via the .mjs file extension, the package.json "type" field with a value "module", the --input-type flag with a value of "module", or the --experimental-default-type flag with a value of "module". These are explicit markers of code being intended to run as an ES module.

相反,作者可以通过 .cjs 文件扩展名、值为 "commonjs"package.json "type" 字段、值为 "commonjs"--input-type 标志或值为 "commonjs"--experimental-default-type 标志,告诉 Node.js 将 JavaScript 解释为 CommonJS。

¥Inversely, authors can tell Node.js to interpret JavaScript as CommonJS via the .cjs file extension, the package.json "type" field with a value "commonjs", the --input-type flag with a value of "commonjs", or the --experimental-default-type flag with a value of "commonjs".

当代码缺少任一模块系统的显式标记时,Node.js 将检查模块的源代码以查找 ES 模块语法。如果找到这样的语法,Node.js 会将代码作为 ES 模块运行;否则它将作为 CommonJS 运行该模块。有关详细信息,请参阅 确定模块系统

¥When code lacks explicit markers for either module system, Node.js will inspect the source code of a module to look for ES module syntax. If such syntax is found, Node.js will run the code as an ES module; otherwise it will run the module as CommonJS. See Determining module system for more details.