Sub topic 3
Dynamic import() creates a chunk
This chapter assumes you know how to define routes with the Angular Router, can read TypeScript import and export statements, and have run ng build before. It covers the one language feature that makes lazy loading possible: the dynamic import() expression.
Static import versus dynamic import
A static import sits at the top of a file. The bundler follows it at build time and puts the imported code in the same output file as the importer.
import { HomeComponent } from './home/home.component';A dynamic import() is an expression that you can call anywhere. It takes a path and returns a Promise that resolves to the module's exports.
const promise = import('./home/home.component');
promise.then(module => console.log(module.HomeComponent));The bundler sees the call at build time and treats the target file as a split point. It writes that file, and everything only it needs, to a separate JavaScript file called a chunk. The browser downloads the chunk when the import() runs, not when the page first loads.
How the router uses it
The router does not call import() for you. You give a route a function that calls it, and the router runs that function the first time the route is needed.
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),
},
];Three details matter here:
- The arrow function wraps the
import(). Without the wrapper, the import would run as soon as the file is evaluated, and nothing would be lazy. .then(m => m.HomeComponent)picks the export the router needs from the module object. The name must match the exported symbol.- The path is a string literal. The bundler must be able to read it at build time to know which file to split out.
The next two chapters cover loadComponent and loadChildren in detail. Here, the point is that both properties accept any function that returns a promise.
What ends up in the chunk
The chunk contains the target file and every file that only it imports. If home.component.ts imports a HomeCardComponent that nothing else uses, that component goes into the same chunk.
Code that other parts of the app also import is shared. The bundler usually moves it into its own common chunk or leaves it in the main bundle. You can see this in the build output, which a later chapter covers.
The bundler decides this by looking at the whole import graph. The effect is that one static import of a lazy file anywhere in the eagerly loaded code pulls it back into the main bundle.
// app.routes.ts
import { HomeComponent } from './home/home.component'; // static: defeats the split
export const routes = [
{
path: '',
loadComponent: () =>
import('./home/home.component').then(m => m.HomeComponent), // dynamic
},
];In this example HomeComponent is in main.js, because the static import wins. The dynamic import still works, but it no longer creates a chunk.
Loading, failure, and caching
Because import() returns a promise, it behaves like any asynchronous network call:
- The first activation of the route waits for the download. Navigation does not complete until the chunk arrives.
- If the download fails, for example because the user is offline or a deployment removed the old file, the promise rejects. The router then fires a
NavigationErrorevent, and the navigation is cancelled. - After the first load, the browser's module system keeps the result. Later navigations to the same route do not download the chunk again.
Chunk file names usually include a content hash, so a new deployment produces new names. A user with an old tab open can request a name that no longer exists on the server. This is a known cause of chunk load errors after deployments.
Summary table
| Feature | Static `import` | Dynamic `import()` |
|---|---|---|
| Where it can appear | Top level of a file | Anywhere in code |
| Result | Bindings available immediately | A `Promise` of the module |
| Effect on the bundle | Code joins the importer's bundle | Code goes into a separate chunk |
| Runs when | The importing file loads | The expression executes |
Exercise
A route is defined as loadComponent: import('./reports/reports.component').then(m => m.ReportsComponent), with no arrow function. The file is not imported anywhere else. Why is this not lazy, and how do you fix it?
Show answer
The import() expression runs immediately when the route array is evaluated, so the download starts at application startup, and loadComponent receives a promise instead of a function. Wrap it in an arrow function: loadComponent: () => import('./reports/reports.component').then(m => m.ReportsComponent). The router then calls the function only when the route is first activated.
Exercise
You add a dynamic import() for ./shop/shop.routes, but the build output shows no separate chunk for it. Name one likely cause and how you would confirm it.
Show answer
Another file in the eagerly loaded code imports something from ./shop/shop.routes (or a file it depends on) with a static import, which keeps the code in the main bundle. Search the project for static imports of that path, for example with a text search for shop.routes, and remove or redirect them.