搭建Create-react-app+react-app-rewired+TypeScript+AntD项目遇编译错误求方案
解决Create-react-app + react-app-rewired + TypeScript + AntD整合问题
我之前整合这几个技术栈的时候也踩过不少坑,尤其是你遇到的这种类型编译错误,给你分享下我亲测有效的完整步骤,应该能帮你搞定:
1. 初始化TypeScript项目
先从官方的TypeScript模板创建项目,避免基础配置缺失:
npx create-react-app my-antd-ts-app --template typescript cd my-antd-ts-app
2. 安装必要依赖
需要安装重写CRA配置的工具、AntD本身,还有实现按需加载的插件:
npm install react-app-rewired customize-cra antd babel-plugin-import --save npm install @types/antd --save-dev
3. 修改package.json的脚本命令
把原来的react-scripts替换成react-app-rewired,这样启动和构建时会加载我们的自定义配置:
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" }
4. 创建自定义配置文件
在项目根目录新建config-overrides.js,配置按需加载和Less支持(方便自定义主题):
const { override, fixBabelImports, addLessLoader } = require('customize-cra'); module.exports = override( // 配置AntD按需加载,自动引入组件对应样式 fixBabelImports('import', { libraryName: 'antd', libraryDirectory: 'es', style: true, // 使用Less源文件,支持主题定制 }), // 配置Less编译,开启JavaScript支持,可选自定义主题变量 addLessLoader({ lessOptions: { javascriptEnabled: true, modifyVars: { '@primary-color': '#1890ff' }, // 替换成你想要的主题色 }, }), );
5. 解决你遇到的类型编译错误
你提到的那个类型不兼容错误,大概率是旧版本的@types/antd和React、TypeScript版本不匹配导致的,试试这几个方案:
- 先更新
@types/antd到最新版本:npm update @types/antd --save-dev - 检查
tsconfig.json,如果开启了strict模式,尝试把strictPropertyInitialization设为false,或者暂时关闭strict(如果项目允许的话):"compilerOptions": { // ...其他配置 "strict": false, // 或者单独设置 "strictPropertyInitialization": false } - 如果还是有问题,可以在使用AntD组件时临时用类型断言绕过:
<Button className="my-btn" style={{ transition: 'all 0.3s', transform: 'scale(1.1)' }} > 测试按钮 </Button> as React.ReactElement
6. 测试运行
在App.tsx里引入一个AntD组件验证:
import React from 'react'; import { Button, Card } from 'antd'; import './App.css'; function App() { return ( <div className="App" style={{ padding: '20px' }}> <Card title="AntD + TypeScript 测试"> <Button type="primary">Hello World!</Button> </Card> </div> ); } export default App;
执行npm start,正常情况下项目就能顺利启动,不会再出现编译错误了。
另外你提到的那个GitHub模板可能版本比较旧,依赖兼容性差,所以更推荐用上面的步骤从头配置,稳定性更高。
内容的提问来源于stack exchange,提问作者zdixon
相关产品推荐
相关产品推荐

