webpack之 code splitting

一、code splitting的意义

web项目越来越重时,打包产生的输出文件越来越大,因为所有的模块都是打包到这个一个文件中,很明显会影响到页面加载的速度。code splitting是指将页面分块打包,按需加载。

二、切割点选择require.ensure

require.ensure(dependencies,callback),回调中异步加载

require.ensure(["module-a", "module-b"], function() {
  var a = require("module-c");
  // ...
},'打包文件的名字');

上例中,module-a,module-b,module-c三个文件打包在一个文件中,module-c虽然不是依赖,但在回调中加载了就要打包

实例:
//index.html
<html>
<head>
    <title></title>
</head>
<body>
    <button id='btn'>hello</button>
    <script type="text/javascript" src='bundle.js'></script>
</body>
</html>

//moduleA.js
export default {
    a:'1111'
}

//entry.js
console.log('hello');
var btn=document.getElementById('btn');
btn.onclick=function(){
    require.ensure([],function(){
        var obj=require('./moduleA.js').default;
        console.log(obj.a);
    });
}

点击按钮前
这里写图片描述

点击按钮后(示例打包文件太小,所以分开打包后并不能看出时间上的优势,可以想象当moduleA.js文件特别大时,分割打包的优势会很明显):
这里写图片描述

三、react-router

react-router是基于React的一个路由库。
提供两种定义路由的形式:

//Plain JavaScript way:
let myRoute = {
  path: `${some path}`,
  childRoutes: [
    RouteA,
    RouteB,
    RouteC,
  ]
}

//declaratively way:
const routes = (
  <Route component={Component}>
    <Route path="pathA" component={ComponentA}/>
    <Route path="pathB" component={ComponentB}/>
  </Route>
)
getComponent

对应于component 属性,但是这个方法是异步的,也就是只有当路由匹配时,才会调用这个方法。

export default [{
    path: 'competitor',

    // redirectTo 一般不与 indexRoute 属性并存
    redirectTo: 'price',

    // competitor 骨架
    getComponent(nextState, cb) {
        require.ensure([], req => {
            cb(null, require('./Index').default);
        }, 'competitor-index');
    },

    // competitor 子路径
    childRoutes: [{
        path: 'price',
        getComponent(nextState, cb) {
            require.ensure([], req => {
                cb(null, require('./Price').default);
            }, 'competitor-price');
        }
    }]
}];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值