Sub topic 12
Pitfalls that defeat lazy loading
This chapter assumes you can already write a loadComponent or loadChildren route and read the output of ng build. Here you will learn how a correct-looking lazy route can still end up in the main bundle, how to notice that, and how to fix it. You will also see the runtime problems that lazy route trees cause.
Lazy loading is a property of the whole import graph
A loadChildren: () => import('./admin/admin.routes') line does not guarantee a separate chunk. It only marks one import as a split point. The bundler builds a graph of every import statement it can reach and decides which file belongs in which chunk.
A file can go in a lazy chunk only if every path to it from the entry point passes through a dynamic import(). If any static import reaches it from eagerly loaded code, the bundler puts it in the main bundle. A bundler normally does this without any error. The build succeeds and the app works. The only symptom is that the main bundle stays large.
Every pitfall below is a variation of this graph problem, except the ones about providers and preloading.
Pitfall 1: A static import from eager code
The most common cause is a harmless-looking import of a constant, a function or a class from inside a lazy feature folder.
// nav.component.ts (part of the eager bundle)
import { Component } from '@angular/core';
import { RouterLink } from '@angular/router';
import { ADMIN_LABEL } from './admin/admin-labels';
@Component({
selector: 'app-nav',
imports: [RouterLink],
template: `<a routerLink="/admin">{{ label }}</a>`,
})
export class NavComponent {
readonly label = ADMIN_LABEL;
}admin-labels.ts is now reachable through a static import. That alone is not a disaster if the file is tiny. The problem grows when admin-labels.ts itself imports something large, such as a chart helper or a data table utility. Those files then move into the main bundle too.
The fix is to move code that eager code needs out of the lazy folder.
// shared/labels.ts
export const ADMIN_LABEL = 'Administration';// nav.component.ts
import { Component } from '@angular/core';
import { RouterLink } from '@angular/router';
import { ADMIN_LABEL } from './shared/labels';
@Component({
selector: 'app-nav',
imports: [RouterLink],
template: `<a routerLink="/admin">{{ label }}</a>`,
})
export class NavComponent {
readonly label = ADMIN_LABEL;
}Make this a convention: eager code may import from shared/, but never from inside a lazy feature folder.
Imports that do not count
TypeScript removes an import that is used only as a type, because it produces no runtime code. An interface or type alias imported from a lazy folder therefore does not pull that file into the main bundle. You can make this explicit with import type.
import type { AdminUser } from './admin/admin-user.model';This is safe, and it fails at compile time if you later use AdminUser as a value. A class used as a value, for example in new AdminUser() or instanceof, is a real import.
Pitfall 2: Barrel files
A barrel is an index.ts that re-exports everything in a folder.
// admin/index.ts
export * from './admin-dashboard.component';
export * from './admin-users.component';
export * from './admin-labels';Importing one constant from './admin' makes the bundler look at the whole barrel. Modern bundlers can drop unused re-exports through tree shaking. That works only when they can prove the modules have no side effects. Classes with decorators, top-level function calls and polyfill-style imports make that proof difficult. Do not rely on it.
Two habits avoid the problem:
- Import from the specific file, not the barrel.
- Do not create barrels for lazy feature folders. A barrel for
shared/is fine, because everything in it is already eager.
Pitfall 3: Mixing `component` and `loadComponent`, or naming the component in a template
A route with component: AdminDashboardComponent needs a static import of that class. Converting a route to loadComponent and leaving the old import line behind is a common half-finished refactor.
// Before: eager
import { AdminDashboardComponent } from './admin/admin-dashboard.component';
{ path: 'admin', component: AdminDashboardComponent }
// After: lazy. The import line above must be deleted.
{
path: 'admin',
loadComponent: () =>
import('./admin/admin-dashboard.component').then(m => m.AdminDashboardComponent),
}If anything else in eager code still needs the unused import, the editor shows no warning and the code still compiles. Search for the component's class name across the project after converting a route. Only the lazy route and the component's own file should mention it.
The same applies to standalone components. If an eager component lists AdminDashboardComponent in its imports array, or uses its selector in an eager template, the component is statically imported and ends up in the main bundle. Reach lazy components through the router, or with a deferred view, which is a different mechanism. Do not add them to an eager component's imports.
Pitfall 4: The same service provided in two places
Providers behave differently across the lazy boundary, and the failure is usually a runtime bug.
A service declared with providedIn: 'root' is tree-shakable. If only lazy code uses it, the bundler places it in the lazy chunk. If eager and lazy code both use it, it goes to the main bundle (or a shared chunk), and everyone shares one instance.
A service listed in a route's providers array gets a new instance in that route's environment injector. That instance exists only for that route tree.
Combining the two gives you two instances.
import { Injectable } from '@angular/core';
import { Routes } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class CartService {
items: string[] = [];
}
export const SHOP_ROUTES: Routes = [
{
path: '',
providers: [CartService], // creates a second CartService for this route tree
loadComponent: () =>
import('./shop.component').then(m => m.ShopComponent),
},
];Components inside the shop route see the route-level CartService. Eager components, such as a header cart badge, see the root one. Adding an item in the shop then leaves the badge unchanged.
Use this rule:
- If the state is shared across the app, use
providedIn: 'root'and do not list the service in routeproviders. - If the state belongs to one feature, list it only in the route's
providers, and do not mark itprovidedIn: 'root'.
The opposite mistake produces NullInjectorError. A service that is only in a lazy route's providers cannot be injected by eager code, because that injector does not exist until the route loads. If eager code needs the service, it is not feature-scoped.
Pitfall 5: NgModule leftovers
In applications that still use NgModules, the classic mistake is declaring the lazy module's route and also importing the module.
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(routes),
LegacyModule, // static import: the lazy route above no longer produces a separate chunk
],
})
export class AppModule {}The loadChildren line in routes is still there, but the module is reachable statically, so it goes in the main bundle. Remove the module from imports.
A related problem is forRoot(). A module that provides singletons through forRoot() must be imported with forRoot() only in the root module. If a lazy module imports it that way too, the lazy module gets its own copy of those services. Use forChild() or a plain import in lazy modules.
Pitfall 6: Preloading everything
PreloadAllModules fetches every lazy chunk in the background after the first navigation. This does not hurt the initial load, but it can defeat the reason you split the bundle.
- A user on a metered connection downloads code for routes they will never visit.
- Chunks for rarely used or role-restricted areas, such as admin, are fetched for everyone.
- On a slow connection, the background downloads compete with the data requests the current page makes.
For an app with a few small routes, PreloadAllModules is fine. For a large app, use a selective strategy that preloads only the routes users are likely to visit next, like the SelectivePreloadingStrategy from the preloading chapter. Measure before choosing. Open the Network panel on a throttled connection and watch what is fetched after first load.
Pitfall 7: Guarding with the wrong guard
canActivate runs after the router has matched the route. For a lazy route, matching means the chunk has already been downloaded. An unauthorized user is redirected, but they have already fetched the code.
// Downloads the chunk, then redirects
{ path: 'admin', canActivate: [authGuard], loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES) }
// Redirects without downloading the chunk
{ path: 'admin', canMatch: [authMatch], loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES) }Use canMatch when you want to keep a chunk from being downloaded. A client-side guard is not a security boundary. The JavaScript is still public, and the server must enforce authorization on every API call.
Pitfall 8: Wrong export name or shape
A dynamic import resolves to the module namespace object. The .then(m => m.X) step must pick an export that exists.
loadComponentneeds a component class (or a default export, if you return the module's default).loadChildrenneeds aRoutesarray, or an NgModule class in older apps.
A misspelled export compiles under some configurations and fails when the route is first activated, with an error saying the router cannot find a component or routes. Test every lazy route by navigating to it. A route that is never visited in development can fail in production.
Finding these problems in the build output
You can detect most of these pitfalls from the build, without reading the code.
- Run
ng buildand read the output. The application builder prints an initial chunk table and a separate "Lazy chunk files" table. - If a feature you expected to be lazy has no entry in the lazy table, a static import is pulling it in.
- If the initial total did not shrink after your refactor, something still reaches the lazy code.
- Run
ng build --stats-jsonand load the generatedstats.jsoninto a bundle analyzer, such as the esbuild bundle size analyzer on esbuild's website. Find your lazy feature's files and check which chunk each one is in. - To find who imports a file, search the project for its path. In the analyzer, the "imported by" information shows the static importer.
Keep the initial total in a note or in your CI logs. A budget in angular.json that fails the build when the initial bundle exceeds a size catches regressions automatically. The budget warns on size only, so it does not tell you which import caused the growth.
Summary table
| Symptom | Likely cause | Fix |
|---|---|---|
| Feature missing from the "Lazy chunk files" table | Static import from eager code, a barrel, or a leftover module import | Import from `shared/`, import from specific files, delete the old import |
| Main bundle did not shrink after converting a route | Old `component:` import still present, or the selector is used in an eager template | Remove the import and reach the component only through the router |
| Header and feature show different data | Service in both `providedIn: 'root'` and route `providers` | Pick one scope |
| `NullInjectorError` in eager code | Service only in a lazy route's `providers` | Move it to root scope |
| Unauthorized users still download the chunk | `canActivate` instead of `canMatch` | Use `canMatch` |
| Large unused downloads after first load | `PreloadAllModules` on a big app | Use a selective strategy |
| Error on first visit to a route | Wrong export name in `.then(...)` | Check the export; navigate to every lazy route |
Exercise
After converting the reports route to loadChildren, ng build shows no "Lazy chunk files" entry for it, and the initial bundle is the same size as before. A search shows that dashboard.component.ts (eager) contains import { REPORT_TYPES } from './reports/report-types';. Why does this keep reports in the main bundle, and what is the fix?
Show answer
The static import makes report-types.ts reachable from eager code, so the bundler places it in the main bundle, along with anything it imports. Move REPORT_TYPES into a file outside the lazy folder, such as shared/report-types.ts, and import it from there in both places. If report-types.ts imports other files from reports/, those must move or be broken out too. Rebuild and confirm that reports appears under "Lazy chunk files".
Exercise
A service CartService is marked providedIn: 'root' and is also listed in the providers array of the lazy shop route. The header badge never updates when the user adds an item in the shop. What is happening, and how do you fix it?
Show answer
The root injector holds one CartService for the header, and the shop route's environment injector creates a second one for the components inside the shop. They have separate state. Remove CartService from the route's providers so that the whole app uses the root instance. If the cart really needs to be feature-scoped, remove providedIn: 'root' instead, and then the header can no longer inject it.