为了优化用户第一次打开首页的速度,很多人都会选择webpack按路由分包js文件,每个路由对应的component懒加载,也就是说只有当用户访问到该路由时,才会加载该模块,这样有效的避免了用户首次进入首页时一次下载所有资源的等待时长。
这里我们使用的是react里面的suspense和lazy。
页面比较多,使用了动态路由加载的方式
话不多说,上代码
(不需要太多自定义功能的话可以直接用 react-router-config(https://github.com/cherijs/react-router-config
),路由渲染这部分就不用自己另外再写了)
renderRoutes.tsx
import React from 'react'
import renderRoutesMap, { RvcRouteConfig } from './renderRoutesMap'
import { Switch, Router } from 'react-router';
import { createBrowserHistory } from 'history';
/**
* renderRoutes 渲染路由
* @param {array} routes 路由列表
*/
const RenderRoutes: React.SFC<{ routes: Array<RvcRouteConfig> }> = (props) => (
<Router history={createBrowserHistory()}>
<Switch >
{renderRoutesMap(props.routes)}
</Switch>
</Router>
)
export default RenderRoutes
renderRoutesMap.tsx
import React, { lazy, Suspense } from 'react'
import {Route,RouteProps} from 'react-router'
export interface RvcRouteConfig {
/**
* 路由名
*/
path: string;
/**
* 是否精确匹配
*/
exact: boolean;
/**
* 需要懒加载的路由绑定模块
*/
lazyComponent?: () => Promise<any>;
/**
* 不需要懒加载的路由绑定模块
*/
component?: any;
}
interface expandRoute extends RouteProps {
key: number;
}
const renderRoutesMap = (routes: Array<RvcRouteConfig>): React.ReactNode[] => {
return routes.map((route:RvcRouteConfig, index) => {
let LoadableComponent = route.lazyComponent ? lazy(route.lazyComponent) : route.component
return (
<Route<expandRoute> key={index} exact={route.exact} path={route.path} render={() => {
return (
// 断言是否需要懒加载
route.lazyComponent ?
<Suspense fallback={<div>Loading……</div>}>
<LoadableComponent />
</Suspense>
: <LoadableComponent />
)
}
}></Route>
)
})
}
export default renderRoutesMap;
routes.ts
import Home from './home/index';
const routes = [
{
path: '/',
exact: true,
//不需要懒加载的模块
component: Home,
},
{
path: '/test',
exact: false,
//需要懒加载的模块
lazyComponent: () => import('./test/index'),
}
]
export default routes;
使用
index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import RenderRoutes from './lazyRoute/renderRoutes';
import routes from './routes';
ReactDOM.render(
<React.StrictMode>
<RenderRoutes routes={routes}/>
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();