How to Use Webpack Bundle Analyzer in NX or Angular Projects


angular nx performance webpack

TL;DR This post explains the same as we can do in Angular or any other Web app

Introduction

In this post, we will discover how to use the Webpack Bundle Analyzer in the NX (Angular) project to analyze your bundles.

Install Webpack Bundle Analyzer

You can install the Webpack Bundle Analyzer using the yarn, npm, or pnpm. In this post, we will use the yarn:

yarn add -D webpack-bundle-analyzer

Add stats-json flag

When an Angular builds the project, it can generate the special stats.json file. This file is understandable for webpack-bundle-analyzer library. To generate this file, we need to add the --stats-json flag to the build command. In the NX project it looks like this:

  "scripts": {
    "ng": "nx",
    "postinstall": "node ./decorate-angular-cli.js && ngcc --properties es2015 browser module main",
    "start": "nx serve",
    // ADD THIS:
    // ...
    "build": "nx build --stats-json",
    // ...
    "test": "nx test"
  },

Build the project with the stats-json flag

Let’s build the project and generate the stats.json file. In the NX project, you can just run the yarn build:

yarn build

Yarn build

The build is generated:

Final build

Add command for analyzing the stats.json

Now we can analyze the stats.json with the webpack-bundle-analyzer. In the NX Workspace, we can add the command for analyzing the stats.json per each project. For example:

  "scripts": {
    "ng": "nx",
    "postinstall": "node ./decorate-angular-cli.js && ngcc --properties es2015 browser module main",
    "start": "nx serve",
    "build": "nx build --stats-json",
    // ADD THIS:
    // ...
    "analyze:app1": "webpack-bundle-analyzer dist/apps/<app1>/stats.json", 
    "analyze:app2": "webpack-bundle-analyzer dist/apps/<app2>/stats.json", 
    //  ...
    "test": "nx test"
  },

Run the webpack-bundle-analyzer

Run the command for your app:

yarn analyze:app

The page will be opened in the browser and you can see the tree of your bundles:

The Webpack Bundle Tree

comments powered by Disqus