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

使用Rollup新JSX功能打包React ESM项目,浏览器报process未定义

解决Rollup打包React应用时process is not defined错误的方案

问题根源

报错的核心原因是:React的npm包中包含了仅Node.js环境存在的process.env变量引用,而浏览器中没有这个全局变量;同时需确保Rollup的JSX转译配置适配React 17+的自动运行时规范。


方案一:使用Rollup原生JSX功能打包

1. 安装必要插件

添加@rollup/plugin-replace来替换代码中的process.env变量:

npm install @rollup/plugin-replace --save-dev

2. 修正Rollup配置

调整rollup.config.mjs,配置原生JSX转译规则并处理环境变量:

import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import replace from "@rollup/plugin-replace";

export default [
    {
        input: 'main.jsx',
        output: {
            file: 'bundle.js',
            format: 'esm',
            exports: 'named',
        },
        // 适配React 17+自动JSX运行时
        jsx: 'react-jsx',
        jsxImportSource: 'react',
        plugins: [
            // 优先替换环境变量,避免后续打包报错
            replace({
                'process.env.NODE_ENV': JSON.stringify('production'),
                preventAssignment: true,
            }),
            nodeResolve({
                extensions: ['.js', '.jsx'], // 确保解析JSX文件
                browser: true, // 优先加载浏览器兼容模块
            }),
            commonjs(),
        ]
    }
];

3. 修正App.jsx内容

你当前的App.jsx存在循环导入问题,替换为基础组件代码:

export default function App() {
    return <h1>Hello React + Rollup</h1>;
}

方案二:使用Babel常规方案打包

若倾向于用Babel处理JSX和语法转译,按以下配置操作:

1. 配置Babel

在项目根目录创建babel.config.json:

{
    "presets": [
        "@babel/preset-react",
        ["@babel/preset-env", { "targets": "defaults" }]
    ]
}

2. 调整Rollup配置

移除原生JSX选项,改用Babel插件处理转译:

import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import replace from "@rollup/plugin-replace";
import babel from "@rollup/plugin-babel";

export default [
    {
        input: 'main.jsx',
        output: {
            file: 'bundle.js',
            format: 'esm',
            exports: 'named',
        },
        plugins: [
            replace({
                'process.env.NODE_ENV': JSON.stringify('production'),
                preventAssignment: true,
            }),
            nodeResolve({
                extensions: ['.js', '.jsx'],
                browser: true,
            }),
            commonjs(),
            babel({
                babelHelpers: 'bundled',
                extensions: ['.js', '.jsx'],
                exclude: 'node_modules/**',
            }),
        ]
    }
];

验证运行

执行rollup -c完成打包后,用浏览器打开index-prod.html即可正常运行。

内容的提问来源于stack exchange,提问作者Riyan Gonsalves

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 11:59:51