如何从Create React App项目中移除TypeScript模板
移除React项目中的TypeScript模板(无需重建项目)
以下是不用重新创建项目就能移除TypeScript的步骤:
卸载TypeScript相关依赖
打开终端,在项目根目录执行卸载命令:# npm 版本 npm uninstall typescript @types/node @types/react @types/react-dom @types/jest # yarn 版本 yarn remove typescript @types/node @types/react @types/react-dom @types/jest修改文件后缀
将项目中所有.ts和.tsx后缀的文件分别改为.js和.jsx,比如:src/App.tsx→src/App.jsxsrc/index.tsx→src/index.jsx- 测试文件如
src/App.test.tsx→src/App.test.jsx
删除TypeScript配置文件
删除项目根目录下的这些文件:tsconfig.jsontsconfig.node.jsonsrc/react-app-env.d.ts(如果存在)
清理代码中的TypeScript语法
去掉所有TypeScript特有的语法,比如:- 变量/函数的类型注解:
const age: number = 25→const age = 25 - 组件props的类型定义:
function User({ name }: { name: string })→function User({ name }) - 接口、类型别名定义:直接删除
interface UserProps { name: string }这类代码 - 类型断言:
const elem = document.getElementById('root') as HTMLElement→const elem = document.getElementById('root')
- 变量/函数的类型注解:
调整package.json(按需)
检查package.json中的scripts字段,删掉任何和TypeScript相关的命令(比如type-check);同时移除package.json中可能存在的types字段。重启项目验证
重新安装依赖后启动项目,确认能正常运行:npm install && npm start # 或者 yarn install && yarn start
内容的提问来源于stack exchange,提问作者Jellyfish
相关产品推荐
相关产品推荐

