承接 ,主要是对上一篇文章中的部分论述进行补充和修正,从属于 。
前文提及,在 webpack 1 中主要是由
进行懒加载,而 Webpack 2 中引入了类似于 SystemJS 的
- bundle-loader
语法,首先我们对于
- System.import
的执行流程进行简单阐述:
- System.import
调用引入的文件及其相关依赖进行单独打包,注意,Webpack 会保证这些独立模块及其依赖不会与主应用的包体相冲突。
- System.import
同样也是 Promise,在请求完成之后
- System.import
会将抓取到的模块作为参数传入
- System.import
中的回调函数。
- then
而 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
- 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:
来源: