@FarmerZ
2016-12-29T00:11:56.000000Z
字数 1958
阅读 523
[toc]
分离 代码库
让我们想一个简单的应用——momentjs,他是一个事件格式化的库。
安装moment.
npm install --save moment
index文件将调用moment作为依赖来记录现在时间。
var moment = require('moment');console.log(moment().format());
我们可以用下面的配置来打包应用。
module.exports = function(env) {return {entry: './index.js',output: {filename: '[chunkhash].[name].js`,path: './dist'}}}
在你的应用中运行webpack,然后检查打包的结果,你会发现moment和index.js被打包合并到bundle.js中了。
对于应用来说这不是我们想要的。如果index.js代码放生了变化,整个bundle.js需要重新打包一遍。浏览器需要重新下载打包后的文件,即使文件的绝大部分都没有变化。
分离moment并且以vendor来命名新的入口能够缓和当前的问题。
module.exports = function(env) {return {entry: {main: './index.js',vendor: 'moment'},output: {filename: '[chunkhash].[name].js`,path: './dist'}}}
运行webpack,你会发现两个被打包的文件被输出。如果你检查的话会发现,moment在这两个文件中都存在。
这是一个非常复杂的插件。他的重要功能从不同的bundle文件中摘除相同的模块,然后绑定到一个bundle文件中。
如果一个公共bundle文件不存在,那么就会创建一个。
我们可如下修改配置文件来使用CommonsChunkPlugin插件。
var webpack = require('webpack');module.exports = function(env) {return {entry: {main: './index.js',vendor: 'moment'},voutput: {filename: '[chunkhash].[name].js`,path: './dist'},plugins: [new webpack.optimize.CommonsChunkPlugin({name: 'vendor' // Specify the common bundle's name.})]}}
现在运行webpack,绑定的检查结果是moment只是被绑定到vendor这个绑定文件中。
应该注意到,如果我们改变应用的代码,然后运行webapck,将会发现vendor绑定文件的也发生了变化。
即使vendor和main两个绑定的问价是分开执行绑定的,一个变化另一个没有变化会导致两个文件的hash
都发生变化。这说明我们还是没有获得浏览器缓存文件的好处,因为文件的hash导致名字都发生了变化。因此他们都会重新下载。
这种问题会出现每次buil的时候。webpack生成一些webpack运行码,它帮助webpack做它的事。当只有一个
bundle绑定文件时,运行码在他的内部。但是有多个bundle被生成时,他在common build中,也就是vendor文件中。
为了解决这个问题,我们需要摘出来一个文件专门存放运行码,这个文件是mainifest file。通过每次创建一个其他的文件--manifest,在它的前面是一大堆我们需要缓存的文件,在vendor中。
var webpack = require('webpack');module.exports = function(env) {return {entry: {main: './index.js',vendor: 'moment'},output: {filename: '[chunkhash].[name].js`,path: './dist'},plugins: [new webpack.optimize.CommonsChunkPlugin({names: ['vendor', 'manifest'] // Specify the common bundle's name.})]}};
通过上面的配置,我们可以看到三个bundle被生成,vendor,main以及manifestbundle。
