前言: 基于ts语言创建react项目,node版本是v16.14.2
一、 脚手架创建项目
- 全局安装
npm install -g creacte-react-app
- 创建项目file-management,ts需要添加–template typescript
npx create-react-app file-management --template typescript
二、 添加craco.config.js配置文件,类似于vue的vue.config.js文件
- 安装
npm i -D @craco/craco
- 在项目根目录添加craco.config.js文件并添加路径别名
const path = require('path')module.exports = {// webpack 配置webpack: {// 配置别名alias: {'@': path.resolve(__dirname, 'src')}}
}
- 修改 package.json 中的脚本命令
修改前:
"scripts": {"start": "react-scripts start","build": "react-scripts build","test": "react-scripts test","eject": "react-scripts eject"},
修改后:
"scripts": {"start": "craco start","build": "craco build","test": "craco test","eject": "craco eject"},
- 配置路径识别,在根目录tsconfig.json文件中添加baseUrl和paths
{"compilerOptions": {"target": "es5","lib": ["dom","dom.iterable","esnext"],"allowJs": true,"skipLibCheck": true,"esModuleInterop": true,"allowSyntheticDefaultImports": true,"strict": true,"forceConsistentCasingInFileNames": true,"noFallthroughCasesInSwitch": true,"module": "esnext","moduleResolution": "node","resolveJsonModule": true,"isolatedModules": true,"noEmit": true,"jsx": "react-jsx","baseUrl": "./","paths": {"@/*": ["src/*"]}},"include": ["src"]
}
更多配置参见craco配置文档