Analyzing Webpack bundles

Have you ever wondered what goes into a Webpack bundle? Why is it as big as it is? We were doing a bit of analysis lately on how to reduce the bundle size and there is a very handy little tool you can use to peek into the bundle: webpack-bundle-analyzer.

What it does is it gives you a very nice graphical representation of the items in the bundle. It is interactive as well so you can zoom in/out and see what gets what.

Setup

  1. add the package to your repo: npm install -D webpack-bundle-analyzer.
  2. Add the the following options to your webpack script --profile —-json stats.json. This will output the stats to stats.json.
  3. Run webpack-bundle-analyzer stats.json from the command line (or just add it as a script in your package.json.

Here’s what your package.json will look like:

"build": "webpack <your options> --profile --json > stats.json",
"build:analyze": "npm run build && npm run webpack-bundle-analyzer stats.json"

This way, you can just run npm run build:analyze which will build your app and then show the analyzer.

Why is this useful

This shows all the external packages we load into our project. One thing that stuck out was lodash. While we do use lodash, we do not use all of it, so this showed somewhere in our code we were importing the entire library vs just the bits we need. This is easy to miss if you import usingimport { map } from 'lodash' vs import map from 'lodash/map' .

A quick fix later our bundle is 500KB smaller:

Not bad. Now, time to go through all the other stuff (I’m looking at you moment.js…).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store