基于 Webpack 2 的 React Router 懒加载路由配置
2023-09-27 14:29:06 时间
基于 Webpack 2 的 React Router 懒加载路由配置承接基于Webpack 2的React组件懒加载,主要是对上一篇文章中的部分论述进行补充和修正,从属于Web 前端入门与工程实践。
前文提及,在 Webpack 1 中主要是由bundle-loader进行懒加载,而 Webpack 2 中引入了类似于 SystemJS 的System.import语法,首先我们对于System.import的执行流程进行简单阐述:
-
Webpack 会在编译过程中扫描代码库时将发现的System.import调用引入的文件及其相关依赖进行单独打包,注意,Webpack 会保证这些独立模块及其依赖不会与主应用的包体相冲突。
-
当我们访问到这些独立打包的组件模块时,Webpack 会发起 JSONP 请求来抓取相关的包体。
-
System.import 同样也是 Promise,在请求完成之后System.import会将抓取到的模块作为参数传入then中的回调函数。
-
如果我们重复访问已经加载完毕的模块,Webpack 不会重复执行抓取与解析的过程。
而 React Router 路由的懒加载实际上分为动态路由与与懒加载两步,典型的所谓动态路由配置如下:
/**
* <Route path="/" component={Core}>
* <IndexRoute component={Home}/>
* <Route path="about" component={About}/>
* <Route path="users" component={Users}>
* <Route path="*" component={Home}/>
* </Route>
*/
export default {
path: '/',
component: Core,
indexRoute: {
getComponent(location, cb) {
...
},
},
childRoutes: [
{
path: 'about',
getComponent(location, cb) {
...
},
},
{
path: 'users',
getComponent(location, cb) {
...
},
},
{
path: '*',
getComponent(location, cb) {
...
},
},
],
};
我们可以在getComponent 回调中以System.js进行动态抓取,笔者自己在Webpack2-React-Redux-Boilerplate定义了一个抽象辅助函数:
const getComponentLazily = (importor, name = 'default') => {
return (location, cb) => {
importor.then((module) => {
//如果是默认模块,则是 module.default
cb(null, module[name]);
})
.catch((err) => {
console.error(`动态路由加载失败:${err}`)
});
}
};
我们也可以将同步路由与异步路由混合使用:
<Route path="/" history={browserHistory} component={Core}>
<IndexRoute component={Home}/>
<Route path="about" component={withRouter(About)}/>
<Route path="users" getComponent={getComponentLazily(System.import('./component/users'),'Users')}/>
<Route path="*" component={withRouter(Home)}/>
</Route>
这样最后打包生成的包体会发现有一个独立的 Chunk:
相关文章
- 丁衣:极路由对智能路由的思考
- 改进YOLO系列 | CVPR2023最新注意力 | BiFormer:视觉变换器与双层路由注意力
- 静态路由配置实例学习记录
- 40.Vue3:嵌套路由配置
- ASP.NET WebApi 路由配置
- 使用Egg.js编写RestfulAPI接口(五)资源路由配置
- vue2借助animate.css实现路由动画效果
- vue安装node以及nrm、nrm配置,路由安装。
- 企业网络的未来:最好的路由,就是没有路由
- vue项目实战:路由文件的配置
- 【Vue路由】props配置、replace属性、编程式路由导航、缓存路由组件
- HCIP-6.5BGP路由聚合原理及配置
- NGINX配置路由转发
- 网络层——AS 间路由选择协议
- centos8配置静态路由