Analyzing Webpack bundles

Panos Voudouris
2 min readFeb 10, 2021

--

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

Setting it up in your repo is very simple. The docs are pretty comprehensive really but here’s a quick summary.

  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

If you need to look at why your bundle size is too big, this tool is a great start. In our case our external packages looked like this:

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…).

--

--

No responses yet