启用


【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”时,后缀为“.js”的文件 包含一个顶层字段"type",值为“commonjs”。

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

  • 副名不是 '.mjs'、'.cjs'、'.json'、'.node' 或 '.js' 的文件 (当最近的父文件“package.json”文件包含顶层字段时 "type" 的值为“module”,这些文件会被识别为 只有当模块被“要求”时才使用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.】