启用


🌐 Enabling

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

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

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

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

  • 具有 .cjs 扩展名的文件;
  • 当最近的父文件“package.json”文件包含顶层字段"type"且值为“commonjs”时,文件扩展名为“.js”。
  • 当最近的父级 package.json 文件不包含顶层字段 "type",或者任何父级文件夹中没有 package.json 时,带有 .js 扩展名或没有扩展名的文件;除非文件包含必须作为 ES 模块评估才能正常工作的语法。即使在所有源都是 CommonJS 的包中,包的作者也应该包含 "type" 字段。明确指出包的 type 将使构建工具和加载器更容易确定包中的文件应该如何解释。
  • 如果文件的扩展名不是 .mjs.cjs.json.node.js(当最近的父级 package.json 文件包含顶层字段 "type" 且其值为 "module" 时,这些文件只有在通过 require() 引入时才会被识别为 CommonJS 模块,而不会在用作程序的命令行入口时被识别)。

有关详细信息,请参见确定模块系统

🌐 See Determining module system for more details.

调用 require() 总是使用 CommonJS 模块加载器。调用 import() 总是使用 ECMAScript 模块加载器。

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