"type"


"type" 字段定义了 Node.js 用于所有 .js 文件的模块格式,这些 .js 文件将该 package.json 文件作为其最近的父文件。

当最近的父 package.json 文件包含值为 "module" 的顶级字段 "type" 时,以 .js 结尾的文件将作为 ES 模块加载。

最近的父 package.json 定义为在当前文件夹中搜索时找到的第一个 package.json,该文件夹的父文件夹,依此类推,直到到达 node_modules 文件夹或卷根。

// package.json
{
  "type": "module"
}
# 在与前面的 package.json 相同的文件夹中
node my-app.js # 作为 ES 模块运行

如果最近的父 package.json 缺少 "type" 字段,或包含 "type": "commonjs",则 .js 文件将被视为 CommonJS。 如果到达卷根目录但未找到 package.json,则将 .js 文件视为 CommonJS

如果最近的父 package.json 包含 "type": "module",则 .js 文件的 import 语句被视为 ES 模块。

// my-app.js, 同上示例的一部分
import './startup.js'; // 由于 package.json 加载为 ES 模块

无论 "type" 字段的值如何,.mjs 文件始终被视为 ES 模块,而 .cjs 文件始终被视为 CommonJS。

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.

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".

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

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.

import statements of .js files are treated as ES modules if the nearest parent package.json contains "type": "module".

// my-app.js, part of the same example as above
import './startup.js'; // Loaded as ES module because of package.json

Regardless of the value of the "type" field, .mjs files are always treated as ES modules and .cjs files are always treated as CommonJS.