Developer Blog

← Home

Optimising JavaScript Bundles with webpack-bundle-analyzer

by Zac Colley

If your JavaScript files are large in size it can take a long time to:

Waiting is not a great user-experience.

So we need to send less JavaScript to our users but sometimes it's hard to know what is in your JavaScript bundle.

The JavaScript output from Webpack can look quite different from the code in your editor.

A tool like Babel converts the JavaScript to ES5 to support older browsers. Your libraries/dependencies will be imported. And after that it can be minified.

How can we tell what we need and don't in our JavaScript bundle?

webpack-bundle-analyzer

This is where Webpack Bundle Analyzer comes in. It can let you see a visual and interactive tree of files.

This includes your dependencies like node_modules. From there you can remove and replace code to make your bundle smaller.

Screenshot of Webpack Bundle Analyzer

For example, you can add this as a plugin in your Webpack config:

const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");

module.exports = {
plugins: [new BundleAnalyzerPlugin()]
};

Then to launch the tool in your browser, you run these commands:

webpack --profile --json > stats.json
webpack-bundle-analyzer bundle/output/path/stats.json

Check out the README for webpack-bundle-analyzer on npm for the full instructions.

An example of optimisation on the Beano website

On Beano.com we use Webpack and have started reducing our JavaScript bundle size.

In February we checked our main bundle size using webpack-bundle-analyzer. It was a disappointing 452.78 KB. (Please don't judge this bundle size, we're working on it... )

One of the first things we noticed was that we had a lot of images inlined in our bundle.

There is a feature of the Webpack loader "url-loader" which lets you embed DataURLs into your JavaScript. An image is inlined if it is under a certain size threshold.

Before we made changes our threshold was at 10000 bytes or 10 KB:

  loader: "url-loader",
options: {
limit: 10000
// ...
}

The idea with url-loader is you can get a performance improvement if the size of the images are small. Doing many different requests for your JavaScript and images can take a while.

Yet we had so many images under this 10 KB threshold it increased the size of our bundle. We changed our threshold to 500 bytes and reduced our main bundle size to from 452.78 KB to 339.96 KB. Yes!

Keep optimising

We hope this post inspires you to have a dig round and reduce the size of your JavaScript bundle.

Remember the best way to avoid this is to write less JavaScript in the first place.