确定模块系统
【Determining module system】
当作为初始输入传递给 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.js 会将所有其他形式的输入例如 .js 文件(其最近的父级 package.json 文件中没有顶层的 "type" 字段)或没有使用 --input-type 标志的字符串输入视为 CommonJS。此行为是为了保持向后兼容性。然而,现在 Node.js 同时支持 CommonJS 和 ES 模块,因此最好在可能的情况下明确指定。Node.js 会在作为初始输入传递给 node 时,或当通过 import 语句、import() 表达式或 require() 表达式引用时,将以下内容视为 CommonJS:
【Node.js will treat as CommonJS all other forms of input, such as .js files
where the nearest parent package.json file contains no top-level "type"
field, or string input without the flag --input-type. This behavior is to
preserve backward compatibility. However, now that Node.js supports both
CommonJS and ES modules, it is best to be explicit whenever possible. Node.js
will treat the following as CommonJS when passed to node as the initial input,
or when referenced by import statements, import() expressions, or
require() expressions:】
- 具有
.cjs扩展名的文件。 - 当最近的父文件“package.json”文件包含顶层字段
"type"且值为“commonjs”时,文件扩展名为“.js”。 - 以参数形式传入
--eval或--print的字符串,或通过STDIN管道传给node,并使用标志--input-type=commonjs。
即使在所有源都是 CommonJS 的包中,包的作者也应该包含 "type" 字段。明确指定包的 type 可以使包在 Node.js 的默认类型发生变化时保持兼容,同时也能让构建工具和加载器更容易确定包中的文件应该如何被解释。
【Package authors should include the "type" field, 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.】