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

Ionic React TS集成Pug.js:react-app-rewired启动tsx报React未定义

解决Ionic React + TypeScript + react-app-rewired中React未定义的问题

我之前碰到过几乎一模一样的场景,问题根源在于transform-react-pug插件生成的JSX代码,在Ionic+TypeScript+react-app-rewired的组合环境里,没有被正确处理React的引用逻辑。下面是具体的解决办法:

问题本质

纯CRA TypeScript项目默认启用了React 17+的自动JSX运行时,转译时会自动处理React的引入,不需要手动写import React from 'react'。但Ionic React项目的初始配置加上react-app-rewired的自定义覆盖,破坏了这个默认行为——transform-react-pug生成的JSX代码找不到全局的React变量,所以抛出了Uncaught ReferenceError: React is not defined。

一步步解决

1. 安装必要的Babel插件

先装@babel/plugin-transform-react-jsx,用来强制启用自动JSX运行时:

npm install @babel/plugin-transform-react-jsx --save-dev

2. 更新config-overrides.js配置

修改你的rewire配置,同时加载transform-react-pug和自动JSX运行时插件:

const { override, disableEsLint, addBabelPlugins } = require('customize-cra')
module.exports = override(
  disableEsLint(),
  addBabelPlugins(
    'transform-react-pug',
    ['@babel/plugin-transform-react-jsx', { runtime: 'automatic' }]
  ),
)

3. 调整TSConfig的JSX模式

打开tsconfig.json,确保jsx选项设置为react-jsx(对应自动运行时规则):

{
  "compilerOptions": {
    // ...其他原有配置
    "jsx": "react-jsx"
  }
}

4. 简化App.tsx(可选)

因为启用了自动运行时,你可以删掉App.tsx里的import React from 'react',代码会更清爽:

import { IonApp, IonContent, IonHeader, IonTitle, IonToolbar, } from '@ionic/react'
declare const pug: any
const App: React.FC = () => {
  return pug`
    IonApp
      IonHeader
        IonToolbar
          IonTitle My App
      IonContent.ion-padding
        Add some content here…
  `
}
export default App

验证效果

重启项目(npm start),你会发现Chrome控制台的错误消失,页面能正常渲染出Ionic的默认布局了。

如果暂时不想用自动运行时,还有个临时方案(不推荐长期用):在pug模板开头手动注入React引用:

const App: React.FC = () => {
  return pug`
    - const React = require('react')
    IonApp
      IonHeader
        IonToolbar
          IonTitle My App
      IonContent.ion-padding
        Add some content here…
  `
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:26:40