Blog>
Snippets

Lazy Loading of Modules

Implement lazy loading for feature modules using Angular's built-in router to reduce the initial load time by only loading modules when they are needed.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  }
  // ... Other routes can be added here
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
This piece of code represents an Angular AppRoutingModule where a feature module is being lazily loaded. The 'loadChildren' function within the routes configuration uses the import statement to dynamically load the 'FeatureModule' when the 'feature' path is navigated to. Only at that point will the associated module be loaded, thus implementing lazy loading.