一、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');
}
}]
}];