Sub topic 5
Lazy loading a feature area with loadChildren
This chapter assumes you can define routes with the Angular Router, use standalone components, and run ng build. It covers loadChildren, which lazy loads a whole group of routes as one chunk.
What loadChildren does
loadComponent lazy loads one component. loadChildren lazy loads a set of child routes. The router calls the function you give it the first time a URL matches the route's path. The function runs a dynamic import(). The bundler emits the imported file and everything only it uses as a separate chunk.
The imported file must export a Routes array. The parent route supplies the URL prefix, and the child array supplies the rest of the path.
Step 1: Export routes from the feature area
Create a file that exports a plain Routes array. It holds the routes for the feature and nothing else.
import { Routes } from '@angular/router';
import { AdminDashboardComponent } from './admin-dashboard.component';
import { AdminUsersComponent } from './admin-users.component';
export const ADMIN_ROUTES: Routes = [
{ path: '', component: AdminDashboardComponent },
{ path: 'users', component: AdminUsersComponent },
];The components here are imported normally. That is correct, because this file is only loaded lazily. Its imports travel with it into the chunk.
Step 2: Point the parent route at it
In the main route config, replace the eager route with loadChildren.
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: '',
loadComponent: () =>
import('./home/home.component').then(m => m.HomeComponent),
},
{
path: 'admin',
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];The .then(m => m.ADMIN_ROUTES) step picks the named export. If the file uses a default export of the routes array, you can write import('./admin/admin.routes') and the router reads default.
With this config, /admin shows AdminDashboardComponent and /admin/users shows AdminUsersComponent. Neither the admin routes file nor its components are in the main bundle.
What happens at navigation time
The first visit waits for the network. Later visits reuse the loaded chunk, so the router does not fetch it again. Navigation does not complete until the chunk arrives, so a slow connection shows a delay. Preloading, covered in a later chapter, removes that delay.
Converting an eager feature to a lazy one
Suppose your app has these routes, all imported at the top of app.routes.ts:
import { Routes } from '@angular/router';
import { AdminDashboardComponent } from './admin/admin-dashboard.component';
import { AdminUsersComponent } from './admin/admin-users.component';
export const routes: Routes = [
{
path: 'admin',
children: [
{ path: '', component: AdminDashboardComponent },
{ path: 'users', component: AdminUsersComponent },
],
},
];To make it lazy:
- Move the
childrenarray into a newadmin.routes.tsthat exports it asADMIN_ROUTES. - Delete the two component imports from
app.routes.ts. - Replace
childrenwith theloadChildrenfunction shown above.
Step 2 matters most. A leftover static import of any admin component keeps that component in the main bundle.
Rules for child routes
- The parent
pathis a prefix.ADMIN_ROUTESshould not repeatadmin. - The parent route can carry its own
canMatch,canActivate,data, orproviders. These apply to the whole lazy tree. - A lazy route array can contain further
loadChildrenorloadComponentroutes, so you can split a large feature into several chunks.
| Property | Loads | Imported value |
|---|---|---|
| `loadComponent` | One standalone component | The component class |
| `loadChildren` | A group of routes | A `Routes` array (or a module in older apps) |
Common errors
- Wrong export name.
m.ADMIN_ROUTESisundefinedif the file exports a different name. The router fails with an error when the route is first visited, not at build time. - Route array not exported. Declaring
const ADMIN_ROUTESwithoutexportgives a compile error on the.thenline. - Duplicated prefix. Putting
path: 'admin'inside both the parent and the child array makes the URL/admin/admin. - Empty child path missing. If the child array has no
path: ''route,/adminalone matches nothing.
Exercise
A developer moves their reports routes into reports.routes.ts and sets loadChildren on the reports route. The build output still shows no separate chunk for reports. What is the most likely cause, and how do you find it?
Show answer
Some eager file still has a static import of reports.routes.ts or one of its components, so the bundler keeps that code in the main bundle. Search the eager code for imports from the reports folder, such as a component used in a template or a shared constant, and remove them or move the shared code into a neutral file.