介绍
【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。 - 包含仅成功解析为ES 模块的语法的代码,如“import”或“export”语句或“import.meta”,且没有明确的解释标记。显式标记包括“.mjs”或“.cjs”扩展,“package.json”“类型”字段,变量为“module”或“commonjs”,或“--input-type”标志。动态“import()”表达式在 CommonJS 或 ES 模块中都支持,且不会强制文件被当作 ES 模块处理。参见语法检测。
当作为初始输入传递给 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。 - 具有
.js扩展名且没有父级package.json文件,或者最近的父级package.json文件缺少type字段的文件,并且代码可以成功作为 CommonJS 进行评估。换句话说,Node.js 会首先尝试将这样的“模糊”文件作为 CommonJS 运行,如果由于解析器发现 ES 模块语法导致作为 CommonJS 的评估失败,它会重试将其作为 ES 模块进行评估。
在“模糊”文件中编写 ES 模块语法会带来性能成本,因此鼓励作者尽可能明确。尤其是,包作者应始终在他们的 package.json 文件中包含 "type" 字段,即使在所有源文件都是 CommonJS 的包中也是如此。明确指定包的 type 可以使包在 Node.js 默认类型发生变化时具有前瞻性,同时也让构建工具和加载器更容易确定包中的文件应如何被解释。
【Writing ES module syntax in "ambiguous" files incurs a performance cost, and
therefore it is encouraged that authors 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.】