--- title: 'react项目打包优化' date: 2021-08-25 11:46:00 --- 优化前: ![](https://img-blog.csdnimg.cn/20210825113401704.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBA5b6Q5ZCM5L-d,size_79,color_FFFFFF,t_70,g_se,x_16) 优化中: ![](https://img-blog.csdnimg.cn/20210825113521714.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBA5b6Q5ZCM5L-d,size_1,color_FFFFFF,t_70,g_se,x_16)![](https://img-blog.csdnimg.cn/20210825113532501.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBA5b6Q5ZCM5L-d,size_79,color_FFFFFF,t_70,g_se,x_16) ![](https://img-blog.csdnimg.cn/20210825113707153.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBA5b6Q5ZCM5L-d,size_79,color_FFFFFF,t_70,g_se,x_16) 优化完成: ![](https://img-blog.csdnimg.cn/202108251138318.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBA5b6Q5ZCM5L-d,size_1,color_FFFFFF,t_70,g_se,x_16)![](https://img-blog.csdnimg.cn/20210825113839735.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBA5b6Q5ZCM5L-d,size_79,color_FFFFFF,t_70,g_se,x_16) ![](https://img-blog.csdnimg.cn/20210825114030970.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBA5b6Q5ZCM5L-d,size_1,color_FFFFFF,t_70,g_se,x_16)![](https://img-blog.csdnimg.cn/20210825114034683.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBA5b6Q5ZCM5L-d,size_79,color_FFFFFF,t_70,g_se,x_16) 要点: 1.路由懒加载 2.在路由懒加载前把自己开发的公共组件全部引入 3.剔除掉比较大的公共组件(例如富文本组件),在业务页面中单独引入 ```javascript import React, { Suspense, lazy } from 'react' import { Switch, Route, Redirect, useHistory } from 'react-router-dom' import Loading from '../components/light/Loading' //自己开发的公共组件会再此处全部引入 import { ErrorBoundary } from '../components/light' const Login = lazy(() => import('../views/light/login/Login')) const SaleLogin = lazy(() => import('../views/sale/login/Login')) const EduLogin = lazy(() => import('../views/edu/login/Login')) const Index = lazy(() => import('../views/light/index/Index')) const NotFound = lazy(() => import('../views/light/notFound/NotFound')) export default function Router() { window.reactRouter = useHistory() return ( <> <ErrorBoundary> <Suspense fallback={<Loading isLazyLoading={true}></Loading>}> <Switch> <Redirect from="/" to="/light/login" exact></Redirect> <Route path="/light/login" component={Login}></Route> <Route path="/sale/login" component={SaleLogin}></Route> <Route path="/edu/login" component={EduLogin}></Route> <Route path="/light/index" component={Index}></Route> <Route path="/sale/index" component={Index}></Route> <Route path="/edu/index" component={Index}></Route> <Route path="/404" component={NotFound}></Route> <Redirect from="*" to="/404" exact></Redirect> </Switch> </Suspense> </ErrorBoundary> <Loading></Loading> </> ) } ```