Sub topic 11
Checking the build output for lazy chunks
You can configure loadComponent or loadChildren correctly and still ship the code in the main bundle. A single stray static import is enough. The router doesn't warn you about this. The build output is where you find out.
This chapter assumes you can run ng build, that you have a standalone-component app with at least one lazy route like the ones in the earlier chapters, and that you know how import() expressions and ES module imports differ. The commands below assume a recent Angular CLI with the default application builder (esbuild-based). Chunk file names and the exact table layout differ between CLI versions and between the esbuild and webpack builders.
What a production build produces
ng build runs a production build by default. It writes the result to dist/<project-name>/browser/. The CLI also prints two tables to the terminal: one for initial chunks and one for lazy chunks.
- Initial chunks are files the browser must download before the app can start. They are referenced from
index.html. Typical entries aremain-<hash>.js,polyfills-<hash>.jsandstyles-<hash>.css. - Lazy chunks are files the browser fetches later, on demand. Each one exists because some
import()expression in your code points at a module that is not already needed at startup.
Here is output from a small app with two lazy routes. The numbers are illustrative, and yours will differ.
Initial chunk files | Names | Raw size | Estimated transfer size
main-4KQ2LZ7P.js | main | 214.80 kB | 58.31 kB
polyfills-FFHMD2TL.js | polyfills | 34.52 kB | 11.28 kB
styles-5INURTSO.css | styles | 0 bytes | 0 bytes
| Initial total | 249.32 kB | 69.59 kB
Lazy chunk files | Names | Raw size | Estimated transfer size
chunk-V3TY6MNA.js | admin-routes | 18.42 kB | 5.77 kB
chunk-HQ2X5RBC.js | home-component | 3.10 kB | 1.34 kBThree columns matter:
- The Initial total is the cost every visitor pays on first load.
- Raw size is the uncompressed size on disk.
- Estimated transfer size approximates the compressed size sent over the network, so use it when you compare against what users actually download.
The Names column in the lazy table is derived from the file that the dynamic import points at. This makes admin-routes easy to match back to ./admin/admin.routes. The mapping is not guaranteed to be readable in every version, so treat it as a hint and not as a contract.
The core check: did a lazy chunk appear?
Run a clean build and read the lazy table.
ng buildFor each loadComponent or loadChildren call you wrote, look for a matching row in the lazy table. There are three outcomes:
| What you see | What it means |
|---|---|
| A lazy chunk whose name matches the feature | The split worked. |
| No lazy table at all | Nothing is being split. Every `import()` target is also reachable by a static import, or you wrote no dynamic imports. |
| A lazy chunk exists, but `main` is still large | The chunk exists, yet something else from the feature is also pulled into `main`. |
The second and third cases are the ones to investigate. A lazy chunk row only proves that some code was split. It doesn't prove that all of the feature's code was.
Measuring the effect with a before-and-after comparison
A lazy chunk is only useful if the initial total drops. The most reliable way to confirm that is to build twice and compare.
- Build the app with the feature routes loaded eagerly (static
component:andchildren:entries) and write down the Initial total. - Convert the feature to
loadComponentorloadChildrenand build again. - Compare the two initial totals. The difference should be close to the size of the new lazy chunk.
If the new lazy chunk is 18 kB but the initial total dropped by only 2 kB, then 16 kB of the feature is still reachable from startup code. That is the signal to go looking for the leak, which the pitfalls section below covers.
Commit the numbers to your notes or a CI log. Bundle size regressions are gradual, and a recorded baseline is the only way to notice them.
Listing chunks yourself
The terminal tables scroll away. When you want a repeatable check, for example in a script, read the output directory directly. This small Node script prints every JavaScript file in the build output, largest first. Save it as list-chunks.mjs in the project root.
import { readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
const dir = process.argv[2] ?? 'dist/my-app/browser';
const files = readdirSync(dir)
.filter((name) => name.endsWith('.js'))
.map((name) => ({ name, kb: statSync(join(dir, name)).size / 1024 }))
.sort((a, b) => b.kb - a.kb);
for (const file of files) {
console.log(`${file.kb.toFixed(1).padStart(8)} kB ${file.name}`);
}Run it after a build, passing your project's output folder if it isn't my-app:
ng build
node list-chunks.mjs dist/my-app/browserThe script reports raw sizes on disk, so its numbers match the Raw size column and not the transfer size. It also can't tell you which files are initial and which are lazy. For that, use index.html: the files it references through <script> and modulepreload tags are the initial set, and everything else is lazy.
Finding out what is inside a chunk
When main is larger than expected, you need to know which modules are in it. The CLI can write a stats file for this:
ng build --stats-jsonThis writes stats.json next to the build output (for the application builder it is placed in the output directory). You can load it into a bundle analyzer. The esbuild-based builder produces an esbuild metafile format, and tools such as the esbuild bundle size analyzer web page read it. Webpack-based builds produce a webpack stats file, which webpack-bundle-analyzer reads. Check which format your builder generates before choosing a tool.
In the analyzer, open the main chunk and look for your feature's files, such as admin-users.component. If they appear in main, something in the startup path imports them statically. Then search the codebase for that file name to find the import.
Using budgets as an automatic check
Budgets turn the manual comparison into a build failure. They live in angular.json under the production configuration.
{
"budgets": [
{
"type": "initial",
"maximumWarning": "300kB",
"maximumError": "400kB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "4kB",
"maximumError": "8kB"
}
]
}The initial budget applies to the total of the initial chunks, which is the number lazy loading is meant to reduce. When it's exceeded, the build prints a warning, or fails for the error limit. Set maximumError a little above your current initial total. If someone later adds a static import that drags a feature back into main, the build fails and points at the problem.
The default budgets in a generated project are generous (around 500 kB warning and 1 MB error). They won't catch a leak in a small app, so tighten them once you have a baseline.
Confirming in the browser
The build output tells you what exists. The browser tells you what is actually requested, and when. Serve the production build (for example with a static file server on dist/my-app/browser) and use the dev tools.
- Open the Network tab, filter by JS, and tick "Disable cache".
- Load the home page. You should see only the initial files, not the chunk for a feature you haven't visited.
- Navigate to a lazy route. A new
chunk-*.jsrequest should appear at that moment. - Navigate away and back. No second request should appear, because the router keeps the loaded route configuration and the browser keeps the module.
If you configured a preloading strategy, step 2 changes. Preloaded chunks are requested shortly after the first navigation, without any user action, so they appear in the network list even though you haven't visited their routes. Check that the preloaded set matches the routes your strategy selects.
Test with ng build output and not ng serve. The development server doesn't produce the same optimized chunking and doesn't minify, so its network behavior and file sizes are not representative.
Pitfalls that show up in the build output
Each of these has a recognizable signature in the numbers.
- A static import of something in the lazy feature. A file in startup code writes
import { AdminService } from './admin/admin.service'and uses it. The bundler must include that file inmain, and it can no longer be in the lazy chunk. Signature: the lazy chunk is smaller than the feature should be, and the feature's files appear inmainin the analyzer. - A barrel file (
index.ts) that re-exports lazy code. Importing one small thing from the barrel can make the bundler keep the other exports reachable frommain. Signature: unrelated feature files inmain. Import from the specific file instead. - An eager route that also references the lazy component. Using the component in a
component:route, or listing it in another component'simports, makes it part of the initial graph, even if a separate route lazy loads it. Signature: theloadComponentroute still works, but no lazy chunk with that component's name appears. - A service provided in root and used by startup code.
providedIn: 'root'services ship wherever they are imported. If both a lazy feature and the shell inject one, it lives inmain. That is often correct for shared services. It is a leak when the service is only meant for the feature, so provide it in the lazy route'sprovidersinstead. - Cached output from an older build. Stale
distfolders can mislead you when you compare file lists. Deletedist/before measuring if the file list looks wrong.
A short verification checklist
Use this after converting any route to lazy loading:
- Run
ng buildand find a lazy chunk row for the feature. - Compare the Initial total with the number from before the change.
- If the drop is much smaller than the lazy chunk, run
ng build --stats-jsonand look for feature files insidemain. - Add or tighten the
initialbudget. - Open the production build in the browser and confirm the chunk is requested only on navigation, or in the background if you use preloading.
Exercise
You convert the admin area to loadChildren. The build prints a lazy chunk named admin-routes of 40 kB, but the Initial total only fell from 310 kB to 305 kB. What does this indicate, and what are your next two steps?
Show answer
About 35 kB of the admin feature is still reachable from startup code, so some file in the initial graph imports it statically. The most likely sources are a direct import of an admin file (such as a service or component) or a barrel file that re-exports it. Next, run ng build --stats-json and open the result in a bundle analyzer to see which admin files sit in main. Then search the codebase for imports of those files from startup code and remove or redirect them. For example, provide the service in the lazy route's providers, or import from the specific file instead of the barrel. Rebuild and confirm the Initial total drops by roughly the chunk size.
Exercise
Why should you check lazy loading behavior against a production build served as static files instead of ng serve, and what should you see in the Network tab for a route protected by a failing canMatch guard?
Show answer
ng serve uses a development configuration that doesn't minify or optimize chunking the way ng build does, so file sizes and request patterns are not representative. For a route whose canMatch guard returns a redirect or false, the Network tab should show no request for that route's lazy chunk, because the guard runs before the router calls the loadChildren function. If the chunk request still appears, the guard isn't being applied to that route.