安装
创建新的含有ts的create-react-app项目
npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript
如果你之前已经通过
npm install -g create-react-app全局安装了create-react-app,我们建议你使用npm uninstall -g create-react-app或yarn global remove create-react-app来卸载这个包,以确保npx总是使用最新的版本。
不再支持全局安装create-react-app。
在已有项目中添加ts
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
# or
yarn add typescript @types/node @types/react @types/react-dom @types/jest
接下来,可以将任何文件重命名为TypeScript文件(例如,将src/index.js重命名为src/index.tsx),并重启服务
类型错误将显示在与构建控制台相同的控制台中。在继续开发或构建项目之前,必须修复这些类型错误。有关高级配置,请参阅这里。
开始使用TypeScript和React
您不需要创建tsconfig.json文件,npm start时将会自动生成它,你可以编辑生成的TypeScript配置。
- TypeScript Handbook
- TypeScript Example on React
- React + TypeScript Cheatsheets 很好地概述了TypeScript与React如何一起使用
故障排除
-
如果你的项目创建时没有启用typeScript, npx可能正在使用
create-react-app的缓存版本。使用npm uninstall -g create-react-app或yarn global Remove create-react-app删除以前安装的版本。再重新npm start启动服务即可。 -
如果你现在正在使用Create - React - App -typescript,请参阅这篇博文了解如何迁移来创建React应用。
-
不支持常量枚举和命名空间,你可以在这里了解TypeScript和Babel一起使用的约束条件。