← All articles

Visualize Ionic/Angular Bundle Files with webpack-bundle-analyzer

Use webpack-bundle-analyzer with ng build --stats-json to size Ionic/Angular lazy-loaded modules and improve UX.

Published
Visualize Ionic/Angular Bundle Files with webpack-bundle-analyzer cover image

This article is part of the Ionic Framework / Capacitor / Stencil Advent Calendar 2021 Advent Calendar 2021, Day 2.


In https://zenn.dev/rdlabo/articles/8ac1bc1be13f16 I wrote that thinking in terms of modules matters. However, there is no clear rule for how many pages or components belong in one module. So let us visualize the project's bundle files with webpack-bundle-analyzer and decide module size from there.

Set Up webpack-bundle-analyzer

Install it with npm. You can install it per project, but I install it globally because it is handy for quick use.

% npm install -g webpack-bundle-analyzer

Now you can run the webpack-bundle-analyzer command.

Build the Project with stats-json

webpack-bundle-analyzer is a visualization tool, and it needs a JSON file with detailed Webpack build output. Angular CLI provides an option for that, so build the project with it.

npm run build -- --stats-json

If your "build": "ng build" script is unchanged, run this command. If you changed or removed it, npx ng build --stats-json does the same thing. This command builds the project and generates www/stats.json at the same time.

Look at the Visualized Bundle Files

Now let us visualize the bundle files with webpack-bundle-analyzer.

webpack-bundle-analyzer www/stats.json

This is a development build, so node_modules dominates. Next, try webpack-bundle-analyzer on a production build.

npm run build -- --stats-json --prod && webpack-bundle-analyzer www/stats.json

This view is easier for comparing module sizes. The main** chunk is the main bundle—the files loaded first when the app starts. You can intuitively see things like "swiper is bigger than I expected" even if @angular and @ionic are unavoidable. Among feature modules, src/app/shared tends to grow larger than others. I trimmed it quite a bit, but it is still large.

Some modules are also too small; that causes load delay at display time, so merging them into modules loaded earlier improves user experience.

Summary

At first you may not tell Ionic component modules from your own project modules, or know what to trim, but I hope you will try visualizing and improving modules to make the app feel better for users.

See you next time.