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

使用Rollup将Node_modules中的React(CJS)转换为ESM模块失败的问题求助

Rollup将Node_modules中的React(CJS)转换为ESM模块失败的问题求助

我正在做一个无构建步骤的前端项目,用的是Buildless React。之前我是通过CDN加载ESM格式的React,写法类似这样:

import React from "https://esm.sh/react"

不过我更倾向于用npm安装React,然后用Rollup把node_modules里的React(CJS格式)打包成ESM格式的文件,这样项目里就能直接引用本地的ESM模块了。

我写了如下的rollup.config.ts配置文件:

import { nodeResolve } from '@rollup/plugin-node-resolve';
import nodePolyfills from 'rollup-plugin-polyfill-node';
import commonjs from '@rollup/plugin-commonjs';

export default {
  input: 'node_modules/react/cjs/react.production.js',
  output: {
    dir: 'node_modules_es',
    format: 'es'
  },
  plugins: [nodeResolve(), nodePolyfills(), commonjs()]
};

执行命令npm run rollup后,生成的/node_modules_es/react.production.js文件里依然存在module.exports代码,这说明从CommonJS到ESM的转换没有成功。

我的package.json配置如下:

{
  "name": "dashboard",
  "version": "1.0.0",
  "main": "js/index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "tsc": "tsc",
    "rollup": "rollup --config rollup.config.ts --configPlugin typescript"
  },
  "author": "",
  "license": "UNLICENSED",
  "private": true,
  "description": "",
  "devDependencies": {
    "@rollup/plugin-commonjs": "^28.0.3",
    "@rollup/plugin-node-resolve": "^16.0.1",
    "@rollup/plugin-typescript": "^12.1.2",
    "rollup": "^4.37.0",
    "rollup-plugin-polyfill-node": "^0.13.0",
    "tslib": "^2.8.1",
    "typescript": "^5.9.2"
  },
  "dependencies": {
    "react": "^19.1.1",
    "react-dom": "^19.1.1"
  }
}

想请教各位:

  • 我想要把React的CJS包转成ESM的需求,用Rollup是否可行?
  • 如果可行的话,我还能尝试哪些调整来解决当前转换失败的问题?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 07:38:11