package.json 和文件扩展名


🌐 package.json and file extensions

在一个包中,package.json "type" 字段定义了 Node.js 应该如何解释 .js 文件。如果 package.json 文件没有 "type" 字段,.js 文件将被视为 CommonJS

🌐 Within a package, the package.json "type" field defines how Node.js should interpret .js files. If a package.json file does not have a "type" field, .js files are treated as CommonJS.

'package.json' '类型''的'“模块”值告诉Node.js解释“.js” 该包内的文件使用ES 模块语法。

🌐 A package.json "type" value of "module" tells Node.js to interpret .js files within that package as using ES module syntax.

"type" 字段不仅适用于初始入口点 (node my-app.js),还适用于通过 import 语句和 import() 表达式引用的文件。

🌐 The "type" field applies not only to initial entry points (node my-app.js) but also to files referenced by import statements and import() expressions.

// my-app.js, treated as an ES module because there is a package.json
// file in the same folder with "type": "module".

import './startup/init.js';
// Loaded as ES module since ./startup contains no package.json file,
// and therefore inherits the "type" value from one level up.

import 'commonjs-package';
// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
// lacks a "type" field or contains "type": "commonjs".

import './node_modules/commonjs-package/index.js';
// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
// lacks a "type" field or contains "type": "commonjs". 

.mjs 结尾的文件总是作为 ES 模块 加载,无论最近的父级 package.json 是什么。

🌐 Files ending with .mjs are always loaded as ES modules regardless of the nearest parent package.json.

.cjs 结尾的文件总是作为 CommonJS 加载,无论最近的父级 package.json 是什么。

🌐 Files ending with .cjs are always loaded as CommonJS regardless of the nearest parent package.json.

import './legacy-file.cjs';
// Loaded as CommonJS since .cjs is always loaded as CommonJS.

import 'commonjs-package/src/index.mjs';
// Loaded as ES module since .mjs is always loaded as ES module. 

.mjs.cjs 扩展名可以在同一个包中混合使用不同类型:

🌐 The .mjs and .cjs extensions can be used to mix types within the same package:

  • 在“type”: “module”包中,Node.js可以通过命名为“.cjs”扩展名来解释某个文件为CommonJS(因为“.js”和“.mjs”文件在“module”包中被视为ES模块)。
  • 在一个 "type": "commonjs" 的包中,可以通过将特定文件命名为 .mjs 扩展名来指示 Node.js 将其解释为 ES 模块(因为在 "commonjs" 包中,.js.cjs 文件都被视为 CommonJS)。