介绍


【Introduction】

当作为初始输入传递给 node,或通过 import 语句或 import() 表达式引用时,Node.js 将把以下内容视为 ES 模块

【Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements or import() expressions:】

  • 具有 .mjs 扩展名的文件。
  • 当最近的父级 package.json 文件包含顶层 "type" 字段且其值为 "module" 时,具有 .js 扩展名的文件。
  • 作为 --eval 参数传入的字符串,或通过 STDIN 管道传递给 node,并使用标志 --input-type=module

当作为初始输入传递给 node,或通过 import 语句或 import() 表达式引用时,Node.js 将把以下内容视为 CommonJS

【Node.js will treat the following as CommonJS when passed to node as the initial input, or when referenced by import statements or import() expressions:】

  • 具有 .cjs 扩展名的文件。
  • 当最近的父文件“package.json”文件包含顶层字段"type"且值为“commonjs”时,文件扩展名为“.js”。
  • 以参数形式传入 --eval--print 的字符串,或通过 STDIN 管道传给 node,并使用标志 --input-type=commonjs

除了这些明确的情况外,还有其他一些情况,Node.js 会根据 --experimental-default-type 标志的值默认使用某一种模块系统:

【Aside from these explicit cases, there are other cases where Node.js defaults to one module system or the other based on the value of the --experimental-default-type flag:】

  • .js 结尾的文件或没有扩展名的文件,如果在同一文件夹或任何父文件夹中没有 package.json 文件存在。
  • .js 结尾的文件或没有扩展名的文件,如果最近的父级 package.json 字段缺少 "type" 字段;除非该文件夹位于 node_modules 文件夹内。(当 package.json 文件缺少 "type" 字段时,node_modules 下的包作用域始终被视为 CommonJS,无论 --experimental-default-type 如何,以保证向后兼容性。)
  • 作为 --eval 参数传入或通过 STDIN 管道传递给 node 的字符串,当未指定 --input-type 时。

此标志当前默认为 "commonjs",但将来可能会更改为默认 "module"。因此,最好在可能的情况下明确指定;特别是,包作者应始终在其 package.json 文件中包含 "type" 字段,即使在所有源都是 CommonJS 的包中也是如此。明确包的 type 可以为包提供未来兼容性,以防 Node.js 的默认类型发生变化,同时也会让构建工具和加载器更容易确定包中的文件应如何解释。

【This flag currently defaults to "commonjs", but it may change in the future to default to "module". For this reason it is best to be explicit wherever possible; in particular, package authors should always include the "type" field in their package.json files, even in packages where all sources are CommonJS. Being explicit about the type of the package will future-proof the package in case the default type of Node.js ever changes, and it will also make things easier for build tools and loaders to determine how the files in the package should be interpreted.】