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

Rollup打包TSX文件时JSX被替换为undefined的配置问题求助

我刚踩过类似的坑,这大概率是JSX转换时没正确绑定React.createElement,再加上Rollup插件顺序、模块格式不匹配导致的。咱们一步步来解决:

第一步:修正TypeScript配置

你的tsconfig里module设为commonjs会和Rollup的ES模块处理逻辑冲突——Rollup对ES模块的支持更友好,能更好地处理依赖树和打包。调整后的配置如下:

{
  "compilerOptions": {
    "allowUnreachableCode": false,
    "alwaysStrict": true,
    "declaration": false,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "lib": ["dom", "esnext"],
    "jsx": "react",
    "module": "ESNext", // 改成ESNext适配Rollup
    "moduleResolution": "node",
    "noFallthroughCasesInSwitch": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "sourceMap": true,
    "strictFunctionTypes": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": true,
    "target": "es5"
  },
  "include": ["src/docs", "typings"],
  "exclude": ["node_modules"]
}

第二步:调整Rollup插件顺序与配置

Rollup是按插件顺序执行的,顺序错了很容易出问题。我们需要先处理环境变量、解析模块、转换CommonJS依赖,最后编译TypeScript。另外别忘了确保@rollup/plugin-commonjs已安装并配置正确——它负责把node_modules里的CommonJS模块(比如React、react-runkit)转成Rollup能处理的ES模块。

调整后的Rollup配置:

import typescript from '@rollup/plugin-typescript';
import resolve from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';
import commonjs from '@rollup/plugin-commonjs';

export default {
  input: 'src/docs/index.tsx',
  output: [
    {
      file: 'src/docs/dist/bundle.js',
      format: 'umd',
      name: 'DocsBundle', // UMD模块的全局名称,方便在HTML里直接引用
      globals: { // 若不想把React等依赖打包进bundle,可指定它们的全局变量名
        react: 'React',
        'react-dom': 'ReactDOM',
        'react-runkit': 'ReactRunkit'
      }
    }
  ],
  // 若要把React等依赖打包进bundle,就删掉下面这行;若想作为外部依赖引入,则保留
  // external: ['react', 'react-dom', 'react-runkit'],
  plugins: [
    replace({
      'process.env.NODE_ENV': JSON.stringify('development'),
      preventAssignment: true // 避免Rollup的赋值警告
    }),
    resolve({
      browser: true, // 优先解析浏览器环境的模块
      extensions: ['.ts', '.tsx', '.js', '.jsx']
    }),
    commonjs({
      include: 'node_modules/**', // 处理所有node_modules里的CommonJS模块
      extensions: ['.js', '.ts']
    }),
    typescript({ tsconfig: './tsconfig.docs.json' })
  ]
};

第三步:验证核心逻辑

你的React导入import * as React from 'react'在旧JSX转换模式(jsx: react)下是正确的,因为JSX会被转译成React.createElement。如果想尝试新的JSX转换(jsx: react-jsx),可以不用显式导入React,但考虑到react-runkit的兼容性,暂时保持旧模式更稳妥。

为什么之前的配置会出问题?

  • 选项1:插件顺序错误——typescript放在了commonjs之后,导致TS编译时,React还没被转成ES模块,JSX无法正确绑定React.createElement,最终变成了undefined。
  • 选项2:把TS的module设为CommonJS,Rollup处理CommonJS模块时容易出现导入丢失的情况,改成ESNext能让Rollup更顺畅地处理依赖关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:11:17