Sub topic 1
Why Split the Bundle
Prerequisites
Assume you know basic Angular components, standalone components, TypeScript imports and exports, and route configuration with the Angular Router. You should also be able to run ng build.
Why split the bundle
An Angular application is delivered as JavaScript files called bundles. The initial bundle must download and run before the first page becomes interactive. If it contains every feature, users download code for screens they may never visit.
Lazy loading splits less-used features into separate files, called chunks. The browser loads a chunk when the router needs it. This reduces the initial download, but it can add a short network delay on the first visit to that route.
Routes as configuration: a quick refresher
A route is a configuration object that maps a URL path to a component. An eagerly loaded route imports its component at the top of the file:
import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
export const routes: Routes = [
{ path: '', component: HomeComponent },
];That static import makes HomeComponent available during the initial build. The bundler can therefore place it in the main bundle.
Dynamic `import()` creates a chunk
A dynamic import() loads a module asynchronously. Angular's build tools recognize it as a split point and emit a separate chunk. The router requests that chunk when the route activates.
Lazy loading a single component with `loadComponent`
Standalone components can be loaded with loadComponent:
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'reports',
loadComponent: () =>
import('./reports/reports.component').then(
m => m.ReportsComponent,
),
},
];The ReportsComponent code is absent from the initial route bundle unless another import includes it. Keep the component's feature-only dependencies behind the same dynamic import so they remain in the lazy chunk.
Exercise
What causes the reports code to become a separate chunk?
Show answer
The dynamic import() inside loadComponent gives the bundler an asynchronous split point.