Open RainZhai opened 7 years ago
2.code-splitting-loader main.js
var $ = require('jquery');
$(function(){
$('input[type=button]').click(function(){
//bundle-loader是一个用来在运行时异步加载模块的loader,使用了bundle-loader加载的文件可以动态的加载
require('bundle-loader!./a.js')(function(content) {
console.log('click');
console.log(content);
});
});
});
3.commonchunkplugin http://www.tuicool.com/articles/UZRF3qM 3.1 对所有依赖的chunk进行公共部分的提取 webpack.config.js
var webpack = require("webpack");
module.exports = {
entry: {
page1: "./page1.js",
page2: "./page2.js"
},
output: {
path: "release",
filename: "[name].[chunkhash].js"
},
plugins: [ new webpack.optimize.CommonsChunkPlugin("common.[chunkhash].js") ]
}
3.2 提取库代码 webpack.config.js
var webpack = require("webpack");
module.exports = {
entry: {
app: "./app.js",
vendor: ["lodash","jquery"],//将各种代码库单独打包到vendor
},
output: {
path: "release",
filename: "[name].[chunkhash].js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({names: ["vendor"]})
]
};
3.3 提取Runtime(运行时)代码 webpack.config.js 使用CommonsChunkPlugin提取代码到新的chunk时,会将webpack运行时(Runtime)也提取到打包后的新的chunk。通过如下配置就可以将webpack的runtime单独提取出来:
var webpack = require("webpack");
module.exports = {
entry: {
app: "./app.js",
vendor: ["lodash","jquery"],
},
output: {
path: 'release',
filename: "[name].[chunkhash].js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({names: ['vendor','runtime']}),
]
};
这种情况下,当业务代码发送变化,而库代码没有改动时,vender的chunkhash不会变,这样才能最大化的利用浏览器的缓存机制。
4.使用DllPlugin和DllReferencePlugin分割代码 webpack.config.js
//在业务代码的webpack配置文件中使用DllReferencePlugin插件引用模块映射文件:vender-menifest.json后,我们可以正常的通过require引入依赖的模块,如果在vender-menifest.json中找到依赖模块的路径映射信息,webpack会直接使用dll包中的该依赖模块,否则将该依赖模块打包到业务chunk中。
var webpack = require('webpack');
module.exports = {
entry: {
app: ['./app'],
},
output: {
filename: '[name].[chunkhash].js',
path: 'build/',
},
plugins: [new webpack.DllReferencePlugin({
context: '.',
manifest: require('./vendor-manifest.json'),
})]
};
vendor-manifest.json
{
"name": "vendor_lib",
"content": {
"./node_modules/.npminstall/lodash/4.17.2/lodash/lodash.js": 1,
"./node_modules/.npminstall/webpack/1.13.3/webpack/buildin/module.js": 2,
"./node_modules/.npminstall/react/15.3.2/react/react.js": 3
}
}
webpack构建速度优化
开发提升 热替换
1.Code Splitting
webpack.config.js
a.js
index.html
webpack会维持一堆代码块modules,代码块0,是所有代码的开端,然后通过id 寻找需要加载的代码块,如果遇到amd加载的代码块,需要把代码块回写到modules里。