Haochuan Liu

@haochuan

Reduce webpack bundle size for production

No indroduction here, starting.

  1. Use the right environment variable
new webpack.DefinePlugin({
‘process.env’: {
‘NODE_ENV’: ‘production’
}
})

2. Use production parameter

webpack -p

3. Advanced uglification

new UglifyJSPlugin({
// options
})

4. Optimizing dependencies import

Instead of import the full dependency:

import _ from ‘lodash’;

Just import what you really need:

import _ from ‘lodash/core’;

5. Use Bundle Analyzer to figure out what increases the size

e.g. Most of the time we should ignore the moment locale files

new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)

6. Extract vendors out of your bundle

module.exports = {
…,
entry: {
app: ‘./src/index.js’,
vendor: [‘react’, ‘moment’, ‘lodash/core’]
},
…,
plugins: [
…,
new webpack.optimize.CommonsChunkPlugin({
name: ‘vendor’
})
]
};

7. Extract vendors out of your bundle

module.exports = {
…,
module: {
rules: [
…,
// css
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: ‘style-loader’,
use: [‘css-loader’]
})
}
]
},
plugins: [
…,
new ExtractTextPlugin(‘style.css’),
]
};

8. Code split by routes

Result per step on one of my project

See ya.

More by Haochuan Liu

Topics of interest

More Related Stories