详解webpack + react + react-router 如何实现懒加载
在Webpack1中主要是由bundle-loader进行懒加载,而Webpack2中引入了类似于SystemJS的System.import语法,首先我们对于System.import的执行流程进行简单阐述:
- Webpack会在编译过程中扫描代码库时将发现的System.import调用引入的文件及其相关依赖进行单独打包,注意,Webpack会保证这些独立模块及其依赖不会与主应用的包体相冲突。
- 当我们访问到这些独立打包的组件模块时,Webpack会发起JSONP请求来抓取相关的包体。
- System.import同样也是Promise,在请求完成之后System.import会将抓取到的模块作为参数传入then中的回调函数。
- 如果我们重复访问已经加载完毕的模块,Webpack不会重复执行抓取与解析的过程。
而ReactRouter路由的懒加载实际上分为动态路由与与懒加载两步,典型的所谓动态路由配置如下:
/** ** * * * * */ exportdefault{ path:'/', component:Core, indexRoute:{ getComponent(location,cb){ ... }, }, childRoutes:[ { path:'about', getComponent(location,cb){ ... }, }, { path:'users', getComponent(location,cb){ ... }, }, { path:'*', getComponent(location,cb){ ... }, }, ], };
正常打包
importIndexPagefrom'./views/app.jsx'
importAboutPagefrom'./views/about.jsx'
exportdefaultfunction({history}){
return(
)
}
这是一个正常打包的路由写法,如果需要分割代码,我们需要改造下路由,借助getComponent和require.ensure
webpack代码分割
exportdefaultfunction({history}){
return(
{
require.ensure([],function(require){
callback(null,require('./HomePage.jsx'))
})
}}/>
{
require.ensure([],function(require){
callback(null,require('./AboutPage.jsx'))
})
}}/>
)
}
这样看来代码有点累,我们稍微改造下
consthome=(location,callback)=>{
require.ensure([],require=>{
callback(null,require('./HomePage.jsx'))
},'home')
}
constabout=(location,callback)=>{
require.ensure([],require=>{
callback(null,require('./AboutPage.jsx'))
},'about')
}
exportdefaultfunction({history}){
return(
)
}
这样看起来是不是简洁了很多
注意:由于webpack的原因,如果直接require('./AboutPage.jsx')不能正常加载,请尝试require('./AboutPage.jsx').default
webpack2代码分割
上面的代码看起来好像都是webpack1的写法,那么webpack2呢?
webpac2就需要借助System.import了
exportdefaultfunction({history}){
return(
{
System.import('./HomePage.jsx').then(component=>{
callback(null,component.default||component)
})
}}/>
{
System.import('./AboutPage.jsx').then(component=>{
callback(null,component.default||component)
})
}}/>
)
}
我们一样可以把上面的代码优化一下
consthome=(location,callback)=>{
System.import('./HomePage.jsx').then(component=>{
callback(null,component.default||component)
})
}
constabout=(location,callback)=>{
System.import('./AboutPage.jsx').then(component=>{
callback(null,component.default||component)
})
}
exportdefault({history})=>{
return(
)
}
webpack2+dva实现路由和models懒加载
constrouterThen=(app,callback,[component,model])=>{
app.model(model.default||model)
callback(null,component.default||component)
}
exportdefault({history,app})=>{
return(
{
Promise.all([
System.import('./views/app.jsx'),
System.import('./models/topics')
]).then(routerThen.bind(null,app,callback))
}}/>
{
Promise.all([
System.import('./views/article.jsx'),
System.import('./models/topic')
]).then(routerThen.bind(null,app,callback))
}}/>
)
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。