You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何package.json的exports字段无法为require()调用做别名映射?

关于package.json exports字段支持CJS/ESM的误解问题

场景说明

我尝试通过package.json的exports字段配置包,使其同时支持CJS和ESM入口。

包结构

package/
  src/
    index.js
    main.cjs
  package.json
  tsconfig.json

包内文件内容

package/src/index.js

console.log('index.js')

package/src/main.cjs

console.log('main.cjs')

package/package.json

{
    "name": "package",
    "type": "module",
    "main": "./src/main.cjs",
    "module": "./src/index.js",
    "exports": {
      ".": {
        "import": "./src/index.js",
        "require": "./src/main.cjs"
      },
      "./index.js": {
        "import": "./src/index.js",
        "require": "./src/main.cjs"
      },
      "./src/index.js": {
        "import": "./src/index.js",
        "require": "./src/main.cjs"
      }
    }
}

package/tsconfig.json

{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext"
  }
}

外部测试环境

我用一个外部包测试上述包,结构如下:

external/
  test.cjs
  package.json
  tsconfig.json

外部文件内容

external/test.cjs

require("../package/src/index.js")

external/package.json

{
    "name": "external",
    "type": "module",
    "main": "./test.cjs"
}

external/tsconfig.json

{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext"
  }
}

运行错误

执行node external/test.cjs时,抛出ERR_REQUIRE_ESM错误:

/external/test.cjs:1
require("../package/src/index.js")
^

Error [ERR_REQUIRE_ESM]: require() of ES Module /package/src/index.js from /external/test.cjs not supported.
index.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /package/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

    at Object.<anonymous> (/external/test.cjs:1:1) {
  code: 'ERR_REQUIRE_ESM'
}

核心疑问

我原本认为exports字段会为包的import和require调用创建别名,所以期望require("../package/src/index.js")会被自动映射到./src/main.cjs,但实际并未生效。我对exports的理解存在哪些错误?

已尝试的方案

  • 将tsconfig.json改为jsconfig.json
  • 使用package.json的imports选项
  • 设置engines选项为node14+
  • 当前Node.js版本为v18.6.0

内容的提问来源于stack exchange,提问作者Trevin Avery

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:07:53