Grouping vendor files with the Webpack CommonsChunkPlugin
The size of the bundle file is 1.1MB! That’s a lot. Most of it is from jQuery and LoDash.
We can optimise caching further if split these files out (they won’t change as often as our app.js).
CommonChunkPlugin will help with this.
First we need to create a separate entry for the vendor files in webpack.config.js. :
// **** webpack.config.js ****
const ..
module.exports = {
entry: {
app: '.js/app.js'
},
output: {
filename: 'bundle.js',
path: resolve(__dirname, 'dist'),
pathinfo: true
},
..
}
change entry
// **** webpack.config.js ****
const ..
module.exports = {
entry: {
app: '.js/app.js',
// 1. ++++ add vender list
vender: ['lodash', 'jquery']
},
output: {
// 2. ++-- update the file references
// note: we could use other shorthands not just 'name'
filename: 'bundle.[name].js',
path: resolve(__dirname, 'dist'),
pathinfo: true
},
..
}
now, webpack creates two files: bundle.app.js and bundle.vender.js.
We need to update index.html as well.
So far, the bundle size is still 1.1MB. we need to add the plugin to webpack.config.js.
The CommonChunkPlugin is built into webpack so we need to include webpack
// **** webpack.config.js ****
// 1. ++++ include webpack
const webpack = require('webpack');
const ..
module.exports = {
entry: { .. }
// 2. ++++ add the plugins property
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor'
})
]
Now we have webpackJsonp is not defined error. But the bundle.js is now only 60Kb.We need to add bundle.vendor.js. (adds
<script src=“/bundle.vendor.js”></script>
The vendor file is huge, but can be cached.
The CommonChunkPlugin still breaks Karma. We need to conditionally load.
Creates a another env in webpack.config.js.
// **** webpack.config.js ****
const webpack = require('webpack');
..
// 1. ++++
const isTest = proess.env.NODE_ENV === 'test'
..
// 2. ++++ then in the plugins, set up so that
// the CommonsChunkPlugin is not used
// in the test environment
plugins: [
isTest ? undefinded : new webpack.optimize.CommonsChunkPlugin({
name: 'vendor'
})
]
// 3. ++++ filter out `undefined` from the plugin names
.filter(p => !!p)