启用


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

默认情况下,Node.js 会将以下内容视为 CommonJS 模块:

  • 扩展名为 .cjs 的文件;

  • 当最近的父 package.json 文件包含值为 "commonjs" 的顶层字段 "type" 时,则扩展名为 .js 的文件。

  • 当最近的父 package.json 文件不包含顶层字段 "type" 时,则扩展名为 .js 的文件。 包作者应该包括 "type" 字段,即使在所有源都是 CommonJS 的包中也是如此。 明确包的 type 将使构建工具和加载器更容易确定包中的文件应该如何解释。

  • 扩展名不是 .mjs.cjs.json.node.js 的文件(当最近的父 package.json 文件包含值为 "module" 的顶级字段 "type" 时,这些文件将被识别为 CommonJS 模块只有当它们是 通过 require() 包含,而不是用作程序的命令行入口点时)。

参阅确定模块系统了解更多详细信息。

调用 require() 始终使用 CommonJS 模块加载器。 调用 import() 始终使用 ECMAScript 模块加载器。

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

By default, Node.js will treat the following as CommonJS modules:

  • Files with a .cjs extension;

  • Files with a .js extension when the nearest parent package.json file contains a top-level field "type" with a value of "commonjs".

  • Files with a .js extension when the nearest parent package.json file doesn't contain a top-level field "type". Package authors should include the "type" field, even in packages where all sources are CommonJS. Being explicit about the type of the package will make things easier for build tools and loaders to determine how the files in the package should be interpreted.

  • Files with an extension that is not .mjs, .cjs, .json, .node, or .js (when the nearest parent package.json file contains a top-level field "type" with a value of "module", those files will be recognized as CommonJS modules only if they are being included via require(), not when used as the command-line entry point of the program).

See Determining module system for more details.

Calling require() always use the CommonJS module loader. Calling import() always use the ECMAScript module loader.