Roots Discourse

How to analyze your Webpack bundle in Sage9


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) {
    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] ( 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.



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


1 Like


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