创建一个react项目
首先需要打开终端,进行vite的引入
yarn create vite
使用react模板创建项目
yarn create vite react-test --template react
cd react-test
yarn
yarn add typescript
yarn dev
配置ts环境
在项目根目录创建文件:tsconfig.json(配置项参考官网)
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"paths": {
"@/*": ["./src/*"],
},
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
在项目根目录创建文件:tsconfig.node.json
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
将main.jsx和app.jsx改成tsx文件,将vite.config.js改为ts
注意:需要修改index.html的引入main文件的扩展名
此时,main.tsx可能会报错(反正我的报错了),需要添加一个节点类型
在vite.config.ts配置别名
yarn add @types/node
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
}
})