1 快速搭建开发环境
官方文档:react+jsx
npx create-react-app react-basic
2 基于Vite创建开发环境
可以快速生成一个 React+TS 的开发环境
npm create vite@latest react-jike -- --template react-ts
说明:
-
npm create vite@latest 固定写法(使用最新版vite初始化项目)
-
注意如果最新的vite要求的node版本比你现在的高的话,会报错。要么升级切换node版本,要么换一个版本的vite
-
-
react-jike 项目名称(自定义)
-
-- --template react-ts 指定模版
3 配置基础路由
初始化路由
采用 react-router-dom 进行配置
-
安装:npm i react-router-dom
-
router
4 配置路径别名
-
vite.config.ts
import { defineConfig } from 'vite'
import react from "@vitejs/plugin-react";
import path from "path";
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
},
},
});
-
安装node类型包(解决上面path引入报错)
npm i @types/node -D
-
修改tsconfig.json文件,加上橙色区域
作用:智能路径提示
5 安装axios
1 安装npm i axios
2 配置拦截器
网上多的是,直接用就行
6 路由懒加载
1 懒加载组件LazyLoad
import { Spin } from "antd";
import { LazyExoticComponent, ReactNode, Suspense } from "react";
/** 路由懒加载,带Spin动画 */
const LazyLoad = (Comp: LazyExoticComponent<any>): ReactNode => {
return (
<Suspense
fallback={
<Spin
size="large"
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
height: "100vh",
}}
/>
}
>
<Comp/>
</Suspense>
);
};
export default LazyLoad;
路由:
import LazyLoad from "@/components/router-wrapper/LazyLoad";
import { Navigate } from "react-router-dom";
import { lazy } from "react";
const homeRoutes = {
path: "/home",
element: LazyLoad(lazy(() => import("@/pages/home"))),
children: [
{
path: "",
element: <Navigate to="/home/plan" replace />
},
{
path: "plan",
element: LazyLoad(lazy(() => import("@/pages/home/home-plan"))),
meta: {
title: "计划"
}
},
{
path: "detail",
element: LazyLoad(lazy(() => import("@/pages/home/home-detail"))),
meta: {
title: "详情"
}
},
{
path: "create",
element: LazyLoad(lazy(() => import("@/pages/home/home-create"))),
meta: {
title: "创建"
}
}
]
}
export default homeRoutes;
入口文件:
import ReactDOM from 'react-dom/client';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import homeRoutes from '@/router/Index'; // 确保路径正确
const App = () => {
return (
<Router>
<Routes>
{/* 添加 homeRoutes 的子路由 */}
<Route path={homeRoutes.path} element={homeRoutes.element}>
{homeRoutes.children.map((child) => (
<Route key={child.path} path={child.path} element={child.element} />
))}
</Route>
</Routes>
</Router>
);
};
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(<App />);