如何安装ts的react项目
安装 TypeScript 的 React 项目
方法一:使用 Create React App 直接生成 TypeScript 模板
运行以下命令创建基于 TypeScript 的 React 项目:
npx create-react-app my-app --template typescript
该命令会自动配置 TypeScript 的依赖和基础设置,生成的项目结构已包含 tsconfig.json 和必要的类型定义。
方法二:在现有 React 项目中添加 TypeScript
对于已存在的 JavaScript React 项目,可通过以下步骤迁移到 TypeScript:
npm install --save typescript @types/react @types/react-dom @types/node
将文件扩展名从 .js 改为 .tsx(组件文件)或 .ts(非组件文件),并创建 tsconfig.json 配置文件。

配置 tsconfig.json
以下是推荐的 React 项目基础配置:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
安装必要的类型定义

根据项目使用的库安装对应的类型声明:
npm install --save-dev @types/react-router-dom @types/styled-components
常见库的类型定义通常以 @types/ 前缀提供。
运行开发服务器
启动 TypeScript 编译和 React 开发服务器:
npm start
Create React App 会自动处理 TypeScript 的编译和热更新。






