Sub topic 3
Dynamic import() creates a chunk
This chapter assumes you can write standalone Angular components, define routes with provideRouter, read TypeScript import and export statements, and run ng build. It explains the mechanism under every lazy route: the dynamic import() expression. Once you understand what it does, loadComponent and loadChildren in the following chapters are small additions.
Static and dynamic imports
A static import sits at the top of a file. The bundler reads it while building, follows it, and puts the imported file in the same bundle as the importer.
import { HomeComponent } from './home/home.component';Every static import is resolved at build time. If app.routes.ts statically imports AdminComponent, the admin code is in the main bundle whether or not anyone visits /admin.
A dynamic import is an expression that you can put anywhere in a function body. It takes a module path and returns a Promise of the module's exports.
const promise = import('./home/home.component');
promise.then(module => {
console.log(module.HomeComponent);
});Three facts matter here:
- The call does not run until the surrounding code runs. Nothing is fetched while the file loads.
- It returns a
Promise, so the result arrives asynchronously. - The promise resolves to a module namespace object. Each
exportin the file is a property of that object, so a component exported asHomeComponentismodule.HomeComponent.
What the bundler does with it
When the Angular CLI builds your app, it scans for import() calls with a string literal path. For each one, it treats the target file as the root of a new chunk. A chunk is a separate JavaScript file that holds that module and everything only it needs.
At run time, the import() call asks the browser to download that file with a network request. When the file arrives and evaluates, the promise resolves. If the same import() runs again, the browser reuses the already loaded module and does not download it a second time.
The diagram below shows the sequence.
Why this reduces the initial bundle
The browser must download, parse, and run the main bundle before the app shows anything. A smaller main bundle means a shorter wait. Code behind an import() is not part of that wait. It is fetched only when the code path runs.
This only helps if the code is not also reachable through a static import. The bundler puts a module in a shared location when two places need it. If app.routes.ts imports AdminComponent statically and also lazy loads the file containing it, the static import wins and the code stays in the main bundle.
Where the router uses it
The router does not need special syntax. A route's loadComponent and loadChildren properties are functions that return a promise. You give them a function that calls import():
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),
},
];Read the first route step by step:
loadComponentholds an arrow function. It does not run when the route table is created, so declaring the route costs nothing.- When the router needs this route, it calls the function. That calls
import('./home/home.component')and starts the download. .then(m => m.HomeComponent)unwraps the module object and returns the component class. The router receives the class and renders it.
The second route works the same way, except the promise resolves to a Routes array. The router adds those child routes under admin.
The router remembers the result after the first load. Later navigations to the same route do not call the loader again.
The path must be a literal
The bundler decides at build time which chunks to emit. It can only do this if it can read the path from the source. Use a plain string:
// Good: the bundler can see the path.
const load = () => import('./reports/reports.routes');
// Problematic: the bundler cannot know which file you mean.
const name = 'reports';
const loadBad = () => import(`./${name}/${name}.routes`);With a computed path, the build may fail or may bundle many files that match a pattern. Keep one explicit import() per lazy target.
Default exports
.then(m => m.HomeComponent) is needed because the module object has one property per export. If a file has a default export, the router can accept the promise without .then:
// admin.routes.ts
import { Routes } from '@angular/router';
import { AdminDashboardComponent } from './admin-dashboard.component';
export default [
{ path: '', component: AdminDashboardComponent },
] satisfies Routes;// app.routes.ts
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'admin',
loadChildren: () => import('./admin/admin.routes'),
},
];The router looks for a default export when the loader returns a module. This is shorter, but named exports make refactors and searches easier. Choose one style and use it across the project.
Errors and failed loads
A dynamic import is a network request, so it can fail. The user may be offline, or a deployment may have replaced the chunk file with a newer version that has a different hashed name. In that case the promise rejects, and the navigation fails.
The router reports this as a navigation error. You can observe it with the NavigationError event on Router.events, or handle it centrally with the withNavigationErrorHandler feature:
import { ApplicationConfig, inject } from '@angular/core';
import {
provideRouter,
Router,
withNavigationErrorHandler,
} from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(
routes,
withNavigationErrorHandler(error => {
console.error('Navigation failed', error);
inject(Router).navigateByUrl('/load-error');
}),
),
],
};Observing the split in the browser
Open the browser developer tools, switch to the Network tab, and filter by JS. Load the app and note which files appear. Then navigate to a lazy route. A new request for a file named like chunk-XXXXXXXX.js appears at that moment. That request is the import() call running.
If no new request appears when you navigate, the code was already in the main bundle. The most common reason is a static import elsewhere, which a later chapter covers in detail.
Summary of the working model
| Concept | What it means |
|---|---|
| Static `import` | Resolved at build time and placed in the same bundle |
| `import()` | An expression that returns a `Promise` of the module |
| Chunk | A separate file the bundler emits for a dynamic import target |
| Loader function | The arrow function you give `loadComponent` or `loadChildren` |
| First use | The point at which the browser downloads the chunk |
Exercise
A route is declared as { path: 'admin', loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES) }, but app.routes.ts also contains the line import { AdminDashboardComponent } from './admin/admin-dashboard.component'; and admin.routes.ts uses that component. The build output shows no separate admin chunk. Why, and how do you fix it?
Show answer
The static import at the top of app.routes.ts makes AdminDashboardComponent reachable from the main entry point, so the bundler includes it in the main bundle. Because of this, the admin code is no longer separate. Remove the static import from app.routes.ts, and make sure no other eagerly loaded file imports the admin files either. The component should be reachable only through the import() call.
Exercise
What does import('./home/home.component') return, and why is .then(m => m.HomeComponent) needed in a loadComponent function?
Show answer
It returns a Promise that resolves to a module namespace object with one property per export of the file. The router needs the component class itself, not the module object, so .then(m => m.HomeComponent) picks that export out of the module.