Roots Discourse

How to analyze your Webpack bundle in Sage9

how-to
sage9
#1

Today I wanted to share with you a quick tip - how to analyze your Webpack bundles. This will let you know what modules are getting bundled and what is being sent to your visitors.

There are various ways to achieve that, today I would like to showcase the simplest one (in my opinion).

All points below are applicable to the newest Sage 9 version - 18th April 2019

1. Installation of Webpack Bundle Analyzer
Let’s start with the installation of Webpack Bundle Analyzer

yarn add -D webpack-bundle-analyzer

(please run it from your theme directory)

2. Package.json modificaton
Add following line into your package.json scripts object. For example somewhere below build:profile... command (line 29)

"build:analyze" : "webpack --progress --config resources/assets/build/webpack.config.js --env.analyze",

3. Edit /resources/assets/build/config.js
Edit config.js file and add following code around line 30 (or anywhere in the config object).

bundleAnalyze: !!(argv.env && argv.env.analyze),

4. Edit resources/assets/build/webpack.config.js
Import the Webpack Analyzer on the top of the file:

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

And around line 199 add the following lines:

if (config.bundleAnalyze) {
  webpackConfig.plugins.push(
    new BundleAnalyzerPlugin()
  );
}

Actually you can place this code “almost” anywhere below the webpackConfig object initialization but for the sake of clarity let’s be strict and use line 199.

And done :wink:
That’s all. From now on you can analyze your bundles and check what is being shipped to production, how many kilobytes your precious libraries are eating and how much it costs your end user. Maybe it will be a good time to finally get rid of that slider?

You can see the analysis by running:

yarn build:analyze 

The browser window should open and show you something like on following [screen] (https://cloud.githubusercontent.com/assets/302213/20628702/93f72404-b338-11e6-92d4-9a365550a701.gif) Screen comes from Webpack Analyzer repository.

In case you need more sophisticated options please visit the Webpack Bundle Analyzer Github Repo.

That’s all! I hope you will find it useful.

12 Likes

#2

Just missing the BundleAnalyzerPlugin import in webpack.config.js:
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

Nice!

1 Like

#3

Ah yes, thank you, I forgot to copy that from my project. At least one person read the tutorial :slight_smile:

0 Likes