1、创建项目
npm create vite 项目名称
选择 react
选择 typescript
关闭严格模式
建议关闭严格模式,因为不能自动检测副作用,有意双重调用。将严格模式注释即可。
2、配置sass
npm install sass
更换所有后缀css为sass
vite.config.ts中注册全局样式
// 配置Scss
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "./src/styles/sassConfig";`,
},
},
},
3、配置路径别名
安装path npm i @types/node --save-dev
在 vite.config.ts 中引入path,并声明快捷字符及其对应文件夹,这里以@表示src目录为例,代码如下:
import { resolve } from "path"
// 配置路径别名
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
},
tsconfig.json,注意:这里的字符与目录一定要与vite.config.ts中的配置保持一致。
{"compilerOptions": {"target": "ES2020","useDefineForClassFields": true,"lib": ["ES2020", "DOM", "DOM.Iterable"],"module": "ESNext","skipLibCheck": true,/* Bundler mode */"moduleResolution": "bundler","allowImportingTsExtensions": true,"resolveJsonModule": true,"isolatedModules": true,"noEmit": true,"jsx": "react-jsx",/* Linting */"strict": true,"noUnusedLocals": true,"noUnusedParameters": true,"noFallthroughCasesInSwitch": true,// 路径别名"baseUrl": ".","paths": {"@/*": ["./src/*"]}},"include": ["src"],"references": [{ "path": "./tsconfig.node.json" }]
}
添加后,再次输入@后,编译器会读取src目录下的资源。
4、配置axios请求
(1)下载axios及类型声明文件
npm install axios @types/axios
(2)根据需求封装axios
// 在项目中创建一个 axios.js 文件import axios from 'axios';
const instance = axios.create({baseURL: 'http://api.example.com', // 你的 API 地址timeout: 5000, // 请求超时时间(毫秒)headers: {'Content-Type': 'application/json', // 设置请求头,根据实际情况修改}
});
// 请求拦截器
instance.interceptors.request.use(config => {// 在发送请求之前做些什么,比如添加 token 等return config;},error => {// 对请求错误做些什么return Promise.reject(error);}
);// 响应拦截器
instance.interceptors.response.use(response => {// 对响应数据做点什么return response.data;},error => {// 对响应错误做点什么return Promise.reject(error);}
);export default instance;
(3)解决跨域
在项目根目录下创建三个文件,分别对应全局环境、开发环境、生产环境。
vite.config.ts中配置跨域
import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import { resolve } from "path"
export default defineConfig(({ mode }) => {const config = loadEnv(mode, "./")return {plugins: [react()],// 配置Scsscss: {preprocessorOptions: {scss: {additionalData: `@import "./src/styles/sassConfig";`,},},},// 配置路径别名resolve: {alias: {"@": resolve(__dirname, "src"),},},// 配置跨域server: {port: 8888,host: "192.168.31.207",proxy: {"/api": {target: config.VITE_TARGET, // 会自动判断当前环境,对应上述三个文件中的targetchangeOrigin: true,rewrite: (path) => path.replace(/^\/api/, ""),},},}}
})
5、配置Antd
安装:npm install antd --save
下载icon:npm install @ant-design/icons --save
国际化
下载完毕后,默认语言为英文,需要在main.ts中注入并配置antd
import ReactDOM from "react-dom/client"
import App from "./App.tsx"
import "./index.scss"
// antd部分
import { ConfigProvider } from "antd"
import "dayjs/locale/zh-cn"
import zhCN from "antd/locale/zh_CN"ReactDOM.createRoot(document.getElementById("root")!).render(<ConfigProvider locale={zhCN}><App /></ConfigProvider>
)
6、配置路由
安装 npm i react-router-dom@6
(1)在src文件目录下创建router文件夹
import type { RouteObject, } from 'react-router-dom';
import { Navigate } from "react-router-dom";
import { lazy } from 'react';const Home = lazy(() => import('@/pages/Home'));
const NotFound = lazy(() => import('@/pages/NotFound'));//使用路由懒加载优化提升const routes: RouteObject[] = [{path: "/",element: <Navigate to="/home" />,},{path: '/404',element: <NotFound />,},{path: '/home',element: <Home />,// children: [// {// index : true,// element: <Home />// },// {// path: "/about",// element: <About />,// children: [// { index : true, element: <AboutIndex />},// { path : "/about/:id", element :<AboutList />}// ]// },// {// path: "/bussiness",// element: <Bussiness />,// }// ]},
];export default routes;
(2)在scr/App.tsx文件中加入
import React from 'react';
import './App.css';
import { useRoutes } from 'react-router';
import routes from './route';function App() {return (<div className="App">{useRoutes(routes)}</div>);
}export default App;
(3)在scr/main.tsx文件中配置路由模式
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(<React.StrictMode><BrowserRouter><App /></BrowserRouter></React.StrictMode>
);