Tips on how to optimize your webpack bundle

Here is a list of ways to reduce the weight of your app's bundle, ordered by most significant to less significant. (Estimated weight reductions are based on a non-compressed bundle)

Install a bundle analyzer

The most important thing to do is installing webpack-bundle-analyzer. This plugin let you see every modules inside all your bundles. It's essential to understand what is going on !

npm install --save-dev webpack-bundle-analyzer

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
 
module.exports = {
  plugins: [
    new BundleAnalyzerPlugin(),
  ]
}

Use CommonsChunkPlugin

It basically looks for duplicated modules across your chunks and move them into a separate common chunk. It's very useful if you have multiple entry points using the same modules. You could also extract all vendors into a common bundle. There is many things you can do, I invite you to check the doc because it really depends on your project.

But here is a basic exemple extracting all modules that are in 2 or more places :

var CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');

module.exports = {
  plugins: [
    new CommonsChunkPlugin({
      name: '/dist/common',
      minChunks: 2,
    }),
  ]
}

Moment.js

By default, all locales will be loaded. To pick only those we need, we gonna use ContextReplacementPlugin like so to include only English and French for example :

var ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');

module.exports = { 
  plugins: [
    new ContextReplacementPlugin(/moment[\/\\]locale$/, /^(en|fr)$/),
  ]
}

Lodash (-0.5 MB)

When you import lodash with import _ from 'lodash', the whole lodash library gets added into your bundle.

You can load only parts that you need like so :

import _filter from 'lodash/filter'

jQuery

Even if you are not using it, it may be included by some of your dependencies. You could include a CDN version of it using a script tag and tell webpack to use this external version instead like so :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
module.exports = {
  externals: {
    jquery: 'jQuery',
  },
}

Andd that's it.

I'll update this list when I find new tips that could benefit a wide range of people :)