← Back to Angular, page 5

angular-0093 · Hard senior

How do you find and reduce what makes an Angular bundle large, using the esbuild application builder, budgets and the stats file?

The application builder (esbuild and Vite) is the default since Angular 17. Run ng build --stats-json, group the output by package to see what dominates, then fix the largest items: lazy load routes and @defer blocks, remove unused imports, avoid heavy libraries, and drop zone.js with zoneless mode. Budgets in angular.json fail the build when sizes grow.

Full answer

Start with measurement, not guesses.

The builder: @angular/build:application uses esbuild for bundling and Vite for the dev server. It produces hashed files for the browser, optional server and prerender output, and with --stats-json it writes stats.json, an esbuild metafile that lists each output file and how many bytes each input module contributed.

Analysis steps:

  1. ng build --stats-json. Read the console table: initial chunks (loaded before the app can start) and lazy chunks (loaded later). Initial size matters most.
  2. Open the stats file in a visualiser (the esbuild bundle size analyzer web page, source-map-explorer with source maps, or your own script as below). Group by package to see which dependency dominates.
  3. Fix the largest items first.

Common fixes:

  • Lazy load routes (loadComponent, loadChildren) and heavy parts of a page with @defer.
  • Import precisely: import { map } from 'rxjs' is tree-shaken, but a whole library imported from a barrel that has side effects may not be. Prefer libraries with ES module builds and sideEffects: false.
  • Replace heavy libraries (moment with date-fns or the Intl API, lodash with native methods or per-function imports).
  • Images: use NgOptimizedImage and modern formats. Fonts: subset them.
  • Zone.js is about 34 KiB of the polyfills in the sample build below. Zoneless mode (stable in 20.2) removes it.
  • Check 3rdpartylicenses.txt and the table for duplicated versions of a package.
  • Production configuration already minifies, tree-shakes, inlines critical CSS, and hashes names. Turn on optimization and avoid shipping source maps to users.

Budgets: angular.json configurations accept budgets with type (initial, anyComponentStyle, bundle, anyScript), maximumWarning and maximumError. The default project sets initial warning at 500 kB and error at 1 MB. Tighten them to your real numbers, so a pull request that adds 80 kB fails in CI with a message instead of passing unnoticed.

Do not forget runtime cost: size is only a proxy. Check Core Web Vitals (LCP, INP), use SSR or prerendering for first paint, and test on a mid-range phone.

typescript
// file: analyze-stats.mjs
import { readFileSync } from 'node:fs';

const statsPath = process.argv[2] ?? 'dist/my-app/stats.json';
const stats = JSON.parse(readFileSync(statsPath, 'utf8'));

function packageOf(file) {
  const marker = 'node_modules/';
  const at = file.lastIndexOf(marker);
  if (at === -1) {
    return 'your code';
  }
  const rest = file.slice(at + marker.length).split('/');
  return rest[0].startsWith('@') ? `${rest[0]}/${rest[1]}` : rest[0];
}

for (const [name, output] of Object.entries(stats.outputs)) {
  if (!name.endsWith('.js')) {
    continue;
  }
  const bytesByPackage = new Map();
  for (const [file, info] of Object.entries(output.inputs)) {
    const pkg = packageOf(file);
    bytesByPackage.set(pkg, (bytesByPackage.get(pkg) ?? 0) + info.bytesInOutput);
  }
  console.log(`${name} (${(output.bytes / 1024).toFixed(1)} KiB)`);
  [...bytesByPackage]
    .sort((a, b) => b[1] - a[1])
    .slice(0, 4)
    .forEach(([pkg, bytes]) => console.log(`  ${pkg.padEnd(24)} ${(bytes / 1024).toFixed(1)} KiB`));
}

// Typical output on a fresh project:
//   main-U464A3LU.js (208.1 KiB)
//     @angular/core            89.7 KiB
//     @angular/router          64.7 KiB
//     your code                17.9 KiB
//     rxjs                     16.7 KiB
//   polyfills-5CFQRCPP.js (33.8 KiB)
//     zone.js                  33.8 KiB

// file: angular.budgets.json
{
  "configurations": {
    "production": {
      "budgets": [
        { "type": "initial", "maximumWarning": "400kB", "maximumError": "600kB" },
        { "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" },
        { "type": "bundle", "name": "admin", "maximumError": "150kB" }
      ],
      "outputHashing": "all"
    }
  }
}

Angular 20.3 with the application builder. The script was run in Node twice with identical output, against the `stats.json` from a real `ng build --stats-json` of a fresh CLI project (main chunk 208.1 KiB raw, polyfills 33.8 KiB, estimated transfer about 70 kB). The numbers in the sample output depend on the project, so run it on yours.

Key points

  • `ng build --stats-json` gives per-module sizes. Group by package and fix the largest first.
  • Lazy load routes and use `@defer`. Import precisely. Replace heavy libraries.
  • Zoneless mode removes zone.js from polyfills.
  • Budgets fail CI when size grows. Measure runtime metrics too.

Common mistakes

  • Optimising without measuring, so effort goes to small items.
  • Setting budgets so high that they never fail.
  • Looking only at total size and ignoring the initial chunk.

Follow-ups

  • What is the difference between the `initial` and `anyComponentStyle` budgets?
  • How does `@defer` change the chunks?
  • How would you find a library that was bundled twice?

Tips

  • Describe a loop: measure, fix the biggest, measure again.
  • Quote a real number from a build you ran.
  • Link bundle size to user metrics, not only to kilobytes.

Evaluation rubric

  • Knows the application builder and the stats file.
  • Lists effective fixes with reasons.
  • Uses budgets and runtime measurements.