react与TS项目如何运行
运行React与TypeScript项目的步骤
确保Node.js已安装(建议版本≥14.0.0),可通过终端输入node -v验证。
全局安装或更新create-react-app工具:
npm install -g create-react-app
使用TypeScript模板创建新项目:
npx create-react-app my-app --template typescript
进入项目目录并启动开发服务器:
cd my-app
npm start
现有项目添加TypeScript支持
安装TypeScript及相关类型声明:
npm install --save typescript @types/react @types/react-dom @types/node
将项目中的.js文件重命名为.tsx(组件文件)或.ts(非组件文件),需手动修改文件扩展名。
配置调整
检查或创建tsconfig.json文件,基础配置示例:
{
"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 start
生产环境构建:
npm run build
运行测试(需配置Jest):
npm test
常见问题解决
类型错误处理:安装缺失的类型声明包,例如:
npm install --save-dev @types/library-name
编译速度优化:在tsconfig.json中设置"incremental": true启用增量编译。
VSCode配置:确保工作区使用项目安装的TypeScript版本,通过命令面板选择"TypeScript: Select TypeScript Version"。







