React项目能否同时兼容.js/.jsx与.ts/.tsx?迁移实操求助
无需 eject 实现 React JS 项目与 TypeScript 逐步兼容方案
针对 react-scripts 5.0.0 的纯 JS React 项目,无需新建项目或 eject,即可实现 JS/TS 文件共存、逐步迁移的目标,具体步骤如下:
1. 安装必要依赖
在项目根目录执行命令,安装 TypeScript 及 React 类型声明:
npm install --save-dev typescript @types/react @types/react-dom # 或使用 yarn yarn add --dev typescript @types/react @types/react-dom
2. 添加 TypeScript 配置文件
在项目根目录创建 tsconfig.json,基础配置如下(关键项已标注):
{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, // 允许 TypeScript 处理 JS 文件,核心兼容开关 "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": false, // 先关闭严格模式,避免现有 JS 文件触发大量类型错误,迁移完成后再开启 "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, // 由 react-scripts 负责编译,无需 TypeScript 输出文件 "jsx": "react-jsx" }, "include": ["src"], // 确保包含所有 src 下的 JS/TS/TSX 文件 "exclude": ["node_modules"] }
3. 解决 JS 导入 TSX 报「module not found」问题
按以下步骤排查修复:
- 去掉导入后缀:在 JS 文件中导入 TSX 组件时,不要加
.tsx后缀,例如:// 正确写法 import MyTSComponent from './components/MyTSComponent'; // 错误写法(会导致找不到模块) // import MyTSComponent from './components/MyTSComponent.tsx'; - 删除冲突配置:如果项目根目录存在
jsconfig.json,建议暂时删除,避免与tsconfig.json的模块解析规则冲突 - 重启开发服务器:修改配置后必须重启
npm start,新配置才会生效
4. 新增 TS 组件与逐步迁移
- 新增 TS 组件:直接创建
.tsx格式的组件,例如:// src/components/MyTSComponent.tsx import React from 'react'; type Props = { title: string; }; const MyTSComponent = ({ title }: Props) => { return <h1>{title}</h1>; }; export default MyTSComponent; - 逐步迁移现有 JS 文件:
- 先将 JS 组件文件后缀从
.js改为.jsx(区分普通 JS 文件与 React 组件) - 逐步为组件添加 PropTypes 做类型约束,再过渡到 TypeScript 类型定义
- 最终将
.jsx文件改为.tsx,完成迁移
- 先将 JS 组件文件后缀从
5. 全量迁移完成后的收尾
当所有文件都迁移为 TS/TSX 后,修改 tsconfig.json 开启严格模式:
{ "compilerOptions": { "allowJs": false, // 关闭 JS 文件兼容 "strict": true // 开启严格类型检查 } }
内容的提问来源于stack exchange,提问作者Shourya Shikhar
相关产品推荐
相关产品推荐

