Rollup配置报错:Node误将CommonJS配置当作ES模块加载
解决Rollup配置文件的ES模块/CommonJS冲突错误
我首次使用Rollup构建React组件库,参照教程配置了rollup.config.js文件,内容如下:
import resolve from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; import typescript from "@rollup/plugin-typescript"; import dts from "rollup-plugin-dts"; const packageJson = require("./package.json"); export default [ { input: "src/index.ts", output: [ { file: packageJson.main, //CommonJS format: "cjs", sourcemap: true, }, { file: packageJson.module, //ES6 format: "esm", sourcemap: true, } ], plugins: [ resolve(), commonjs(), typescript({ tsconfig: "./tsconfig.json" }), ] }, { input: "dist/esm/types/index.d.ts", output: [{ file: "dist/index.d.ts", format: "esm" }], plugins: [dts()], } ];
运行Rollup时出现错误:RollupError: Node tried to load your configuration as an ES module even though it is likely CommonJS,尝试过修改文件扩展名或使用提示的标志,但解决方案均无效,请问该如何解决?
解决步骤
1. 统一配置文件的模块语法
错误核心是配置文件混用了ES模块的import和CommonJS的require,Node解析时出现冲突。把读取package.json的代码改成ES模块兼容的写法:
// 方法1:Node 17.1+ 支持的JSON导入语法 import packageJson from "./package.json" assert { type: "json" }; // 方法2:兼容低版本Node的写法 import fs from "fs"; const packageJson = JSON.parse(fs.readFileSync("./package.json", "utf8"));
2. 确认package.json的模块类型配置
- 如果你的项目要以ES模块运行,在
package.json里添加:
此时配置文件保持"type": "module".js扩展名即可。 - 如果不想全局设置ES模块,把配置文件重命名为
rollup.config.mjs,Node会自动按ES模块解析它。
3. 调整dts插件的输入路径(可选优化)
原配置中依赖dist/esm/types/index.d.ts生成,可能因为类型文件生成时机问题导致报错,可以直接用源码入口作为dts的输入,让插件自动处理类型:
{ input: "src/index.ts", output: [{ file: "dist/index.d.ts", format: "esm" }], plugins: [dts()], }
4. 检查依赖版本兼容性
确保Rollup版本在v3以上,同时rollup-plugin-dts、@rollup/plugin-typescript等插件都是最新版,避免版本不兼容导致的解析问题。
修改后的完整配置示例
import resolve from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; import typescript from "@rollup/plugin-typescript"; import dts from "rollup-plugin-dts"; import packageJson from "./package.json" assert { type: "json" }; export default [ { input: "src/index.ts", output: [ { file: packageJson.main, format: "cjs", sourcemap: true, }, { file: packageJson.module, format: "esm", sourcemap: true, } ], plugins: [ resolve(), commonjs(), typescript({ tsconfig: "./tsconfig.json" }), ] }, { input: "src/index.ts", output: [{ file: "dist/index.d.ts", format: "esm" }], plugins: [dts()], } ];
内容的提问来源于stack exchange,提问作者Laura Silvani
相关产品推荐
相关产品推荐

