Sub topic 12
Pitfalls that defeat lazy loading
This chapter assumes you can define routes with the Angular Router, write standalone components, and run ng build. It covers the mistakes that quietly pull lazy code back into the main bundle, and how to spot each one.
How a lazy chunk gets pulled back
A bundler decides what goes in a chunk by following imports. A dynamic import() creates a split point. A static import statement anywhere in the eager part of the app tells the bundler to include that file in the main bundle. Nearly every pitfall below is one of these static imports in the wrong place.
Pitfall 1: Importing lazy code statically
This is the most common mistake. A route file uses loadChildren, but another file imports something from the same feature area.
// app.component.ts (eager)
import { AdminService } from './admin/admin.service';Because app.component.ts is part of the main bundle, admin.service.ts and everything it imports now ship in the main bundle too. The lazy chunk still exists, but it is smaller than you planned.
The fix is to move shared code into a location that both sides can import deliberately, such as a shared/ folder. Keep it small, because anything eager code imports from there becomes part of the main bundle.
Pitfall 2: Referencing a lazy component directly
Both of these in the same routes file defeat the split:
import { Routes } from '@angular/router';
import { ReportsComponent } from './reports/reports.component';
export const routes: Routes = [
{
path: 'reports',
loadComponent: () =>
import('./reports/reports.component').then(m => m.ReportsComponent),
},
];
export const unused = ReportsComponent;The static import on line 2 wins, even if you never use the name. Use only the dynamic form. Angular's compiler also warns when a component is both statically imported and lazy-loaded, so read build warnings.
Pitfall 3: Listing a lazy component in `imports`
Standalone components list the components they use in imports. If an eager component's template uses <app-admin-panel>, the class must be imported statically. That puts the admin panel in the main bundle, whatever the router says. Lazy components should be reached through the router, not rendered from eager templates. For a component that must appear inside an eager template but load later, use @defer, which creates its own split point.
Pitfall 4: Providing services in the wrong place
Where a service is registered affects whether it is eager or lazy.
| Registration | Where it lives |
|---|---|
| `providedIn: 'root'`, injected only in lazy code | Lazy chunk (tree-shaken out of main) |
| `providedIn: 'root'`, injected by eager code | Main bundle |
| Listed in `providers` of `app.config.ts` | Main bundle |
| Listed in `providers` of a lazy route | Lazy chunk, with its own instance |
Two surprises follow. First, listing a service in the application config imports it statically, so the service moves into the main bundle. Second, a service in a lazy route's providers is a separate instance from a root one. If eager code injects a root-provided AdminService and the lazy route also lists it in providers, the two sides hold different instances and different state.
Pitfall 5: Barrel files
A barrel file is an index.ts that re-exports everything in a folder.
// admin/index.ts
export * from './admin.service';
export * from './admin-dashboard.component';
export * from './admin-users.component';If eager code writes import { AdminService } from './admin', the bundler may not be able to prove the other exports are unused. Import from the specific file instead, and avoid barrels that mix eager and lazy code.
Pitfall 6: Guards that load the chunk anyway
A canActivate guard runs after the route has matched, and for loadChildren the router has to load the chunk before it can activate child routes. An unauthorized user therefore downloads the code and is then blocked. Use canMatch to stop the download.
Preloading has a similar effect. PreloadAllModules fetches every lazy chunk in the background, including ones the user is never allowed to see. Prefer a selective strategy for sensitive or very large areas.
Pitfall 7: Never checking the output
None of these mistakes raise an error. The app works and is just larger than it should be. After any routing change, run a production build and compare:
ng buildLook for a "Lazy chunk files" section in the output with one entry per lazy route. Then check that the "Initial chunk files" total did not grow. If a lazy chunk you expect is missing, search your eager code for static imports of that feature.
Checklist
- Each lazy feature is reached only through
import()in a route. - No eager file imports from a lazy feature folder.
- Shared code is in a small, deliberate location.
- Services used by one lazy area are provided in that route's
providers, or areprovidedIn: 'root'and injected only from lazy code. - Sensitive areas use
canMatch. - The build output shows the lazy chunk and a stable initial size.
Exercise
A team lazy loads admin with loadChildren, but the production build shows no separate admin chunk and the main bundle grew. Name two likely causes and how you would confirm each.
Show answer
One cause is a static import of an admin file from eager code, such as AdminService imported in app.component.ts, or a static import of the admin routes in app.routes.ts alongside the import(). Confirm by searching eager files for imports from ./admin. Another cause is a barrel file (admin/index.ts) that eager code imports from, or an admin service listed in app.config.ts providers. Confirm by checking the application config and any imports of the barrel. In both cases, fix the static import and rebuild to see whether an admin entry appears under "Lazy chunk files".