Back to results for “Architecture”
Angular › NgModules & Modular Architecture

How do you lazy load a feature module so its code is only downloaded when a user actually navigates to it?

Intermediate

Answer

You configure the router to load a module using loadChildren with a dynamic import statement, rather than directly importing and declaring the module upfront, telling Angular to only download that module's code the first time a user visits a route belonging to it.
const routes: Routes = [
  { path: 'orders', loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule) }
];
Real-world example A large admin panel only downloads the code for its rarely visited reports section the first time a user actually navigates there, thanks to lazy loading that specific feature module instead of including it in the app's initial bundle.

Common follow-ups: How does lazy loading a module differ from lazy loading an individual standalone component?;What is a good rule of thumb for deciding which feature areas are worth lazy loading?