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

如何解决CommonJS环境下require导入ES模块的ERR_REQUIRE_ESM错误?

问题修复方案

错误的核心原因是:你在根目录package.json中设置了"type": "module",这会让Node.js把包内所有.js文件都当作ES模块处理,但dist/commonjs/bundle.js是Rollup打包出的CommonJS格式文件,用require()导入自然会触发ERR_REQUIRE_ESM错误。

不需要把根目录package.json的"type": "module"改成"type": "commonjs"——那样会反过来导致ESM用户无法正常导入你的库。推荐以下两种修复方案:

方案一:修改CommonJS输出文件后缀为.cjs(推荐)

Node.js会自动识别.cjs后缀的文件为CommonJS模块,不受上层"type": "module"的影响。

  1. 修改Rollup配置文件
    更新rollup.config.js中CommonJS打包的输出文件名:
// rollup.config.js
export default [
  {
    input: "./src/index.js",
    output: {
      format: "cjs",
      file: "./dist/commonjs/bundle.cjs", // 把.js改成.cjs
      sourcemap: true,
    },
  },
  {
    input: "./src/index.js",
    output: {
      format: "es",
      file: "./dist/esm/bundle.mjs",
      sourcemap: true,
    },
  },
];
  1. 更新package.json配置
    同步修改exports和main字段的路径:
// package.json
{
  // ...其他配置
  "exports": {
    ".": {
      "require": "./dist/commonjs/bundle.cjs", // 对应修改为.cjs
      "import": "./dist/esm/bundle.mjs"
    }
  },
  "main": "./dist/commonjs/bundle.cjs", // 同样修改为.cjs
  // ...其他配置
}

重新执行npm run build后,CommonJS用户用require('mockito')就能正常导入了。

方案二:给CommonJS输出目录单独设置package.json

在dist/commonjs目录下新建一个package.json,明确声明该目录下的文件为CommonJS类型:

// dist/commonjs/package.json
{
  "type": "commonjs"
}

这个方法不需要修改文件名和根目录配置,Node.js会优先读取子目录的package.json来判断模块类型,从而把bundle.js识别为CommonJS模块。

两种方案都能解决问题,方案一更符合Node.js的模块规范,方案二更适合不想修改文件名的场景。

内容的提问来源于stack exchange,提问作者Byeongin Yoon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:15:35