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

Electron Forge集成React时HTML渲染失败问题求助

Electron Forge集成React+TypeScript时JSX编译错误解决

问题背景

按照官方指南搭建Electron Forge+React+TypeScript项目,运行npm install时出现JSX解析错误,例如root.render(<h2>Hello from React!</h2>)被错误解析为root.render(Hello, from, React < /h2>););,触发未终止正则表达式、缺少逗号等TypeScript编译错误。

核心代码

index.html

<body>
    <div id="root"></div>
  </body>
</html>

renderer.ts

const rootElement = document.getElementById("root")
const root = createRoot(rootElement)
root.render(<h2>Hello from React!</h2>)

tsconfig.json

{
  "compilerOptions": {
    "target": "ES6",
    "allowJs": true,
    "module": "commonjs",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "noImplicitAny": true,
    "sourceMap": true,
    "baseUrl": ".",
    "outDir": "dist",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "jsx": "react-jsx",
    "paths": {
      "*": ["node_modules/*"]
    }
  },
  "include": ["src/**/*"]
}

解决步骤

  1. 重命名渲染器文件后缀
    将renderer.ts改为renderer.tsx。TypeScript默认仅对.tsx后缀的文件启用JSX语法解析,.ts文件中的JSX会被当作普通TS代码处理,直接引发语法错误。

  2. 补全依赖包
    确保安装了React核心库及类型定义,执行:

    npm install react react-dom @types/react @types/react-dom --save
    

    缺失依赖会导致TypeScript无法识别JSX相关语法。

  3. 检查Webpack配置(若使用webpack模板)
    确认webpack.renderer.config.js中正确配置了TSX文件的处理规则:

    module.exports = {
      module: {
        rules: [
          {
            test: /\.tsx?$/,
            exclude: /node_modules/,
            loader: 'ts-loader'
          }
        ]
      },
      resolve: {
        extensions: ['.tsx', '.ts', '.js']
      }
    }
    

    该配置确保Webpack能识别并编译TSX文件。

  4. 验证tsconfig配置
    确认tsconfig.json中jsx字段设置为react-jsx(React 17+推荐)或react,且include字段覆盖了所有TS/TSX文件路径(如src/**/*),保证配置能作用到目标文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:42:41