"type"
- 类型:<string>
"type" 字段定义了 Node.js 用于所有以该 package.json 文件作为最近父级的 .js 文件的模块格式。
【The "type" field defines the module format that Node.js uses for all
.js files that have that package.json file as their nearest parent.】
当最近的上级 package.json 文件包含顶层字段 "type" 且值为 "module" 时,以 .js 结尾的文件将作为 ES 模块加载。
【Files ending with .js are loaded as ES modules when the nearest parent
package.json file contains a top-level field "type" with a value of
"module".】
最近的父级 package.json 定义为在当前文件夹、该文件夹的父文件夹以及依次向上搜索时找到的第一个 package.json,直到遇到 node_modules 文件夹或卷根目录为止。
【The nearest parent package.json is defined as the first package.json found
when searching in the current folder, that folder's parent, and so on up
until a node_modules folder or the volume root is reached.】
// package.json
{
"type": "module"
} # In same folder as preceding package.json
node my-app.js # Runs as ES module 如果最近的父级 package.json 缺少 "type" 字段,或者包含 "type": "commonjs",则 .js 文件被视为 CommonJS。如果到达卷根目录仍未找到 package.json,则 .js 文件被视为 CommonJS。
【If the nearest parent package.json lacks a "type" field, or contains
"type": "commonjs", .js files are treated as CommonJS. If the volume
root is reached and no package.json is found, .js files are treated as
CommonJS.】
如果最近的父级 package.json 包含 "type": "module",则 .js 文件的 import 语句会被视为 ES 模块。
// my-app.js, part of the same example as above
import './startup.js'; // Loaded as ES module because of package.json 无论 "type" 字段的值如何,.mjs 文件始终被视为 ES 模块,而 .cjs 文件始终被视为 CommonJS。
【Regardless of the value of the "type" field, .mjs files are always treated
as ES modules and .cjs files are always treated as CommonJS.】