配置路径别名
tsconfig.json
{"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"}]
}
vite.config.ts
先安装依赖:
yarn add -D @types/nod
再进行配置:
import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react-swc'
import path from "path"// https://vitejs.dev/config/
export default defineConfig({plugins: [react()],server: {host: "127.0.0.1",port: 5173,proxy: {"/api": "http://127.0.0.1:8888",}},resolve: {alias: {"@": path.resolve(__dirname, "./src")}}
})
整合 antd
安装依赖
yarn add antd
优化404错误页面
修改 src/page/Error404.tsx
import {Button, Result} from "antd";
import {useNavigate} from "react-router-dom";function Error404() {const navigate = useNavigate()const handleClick = () => {navigate("/")}return (<Resultstatus={404}title="404"subTitle="抱歉,您访问的页面不存在"extra={<Button type="primary" onClick={handleClick}>返回首页</Button>}/>)
}export default Error404
此时访问:http://localhost:5173/404
优化403错误页面
修改 src/page/Error403.tsx
import {Button, Result} from "antd";
import {useNavigate} from "react-router-dom";function Error403() {const navigate = useNavigate()const handleClick = () => {navigate("/")}return (<Resultstatus={403}title="403"subTitle="抱歉,您当前没有权限访问此页面"extra={<Button type="primary" onClick={handleClick}>返回首页</Button>}/>)
}export default Error403
此时访问:http://localhost:5173/403
使用API路由
src/router/index.tsx
import {Navigate, useRoutes} from "react-router-dom";
import Index from "../page/Index.tsx";
import Login from "../page/Login.tsx";
import Error404 from "../page/Error404.tsx";
import Error403 from "../page/Error403.tsx";const routers = [{path: "/",element: <Index/>},{path: "/login",element: <Login/>},{path: "/404",element: <Error404/>},{path: "/403",element: <Error403/>},{path: "*",element: <Navigate to="/404"/>},
]export default function Router(){return useRoutes(routers)
}
src/App.tsx
import {BrowserRouter} from "react-router-dom";
import Router from "./router";function App() {return (<BrowserRouter><Router/></BrowserRouter>)
}export default App
测试
此时访问:
- http://localhost:5173/403
- http://localhost:5173/404
整合 axios
安装依赖
yarn add axios
封装请求实例
新增 src/api/request.ts
import axios from "axios";// 创建实例
const req = axios.create({baseURL: '/api',timeout: 3000,timeoutErrorMessage: "请求超时,请稍后再试",withCredentials: true, // 跨域headers: {'Content-Type': 'application/json',}
})// GET 请求
function get(url: string, params: any) {return req.get(url, {params})
}// POST 请求
function post(url: string, data: any) {return req.post(url, data)
}// 导出
export default {req,get,post,
}