Blog>
Snippets

Implementing Lazy Loading in a Monorepo

An example of setting up lazy loading for feature modules in an Angular monorepo to optimize performance and loading times.
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'feature',
    loadChildren: () => import('./path-to-feature/feature.module').then(m => m.FeatureModule)
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
This code sets up a route configuration within an Angular application where the 'feature' route is configured to lazily load a feature module. The loadChildren property is a function that uses the dynamic import() syntax to load the FeatureModule only when the route is navigated to.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';

// Define child routes for lazy-loaded module
const featureRoutes: Routes = [
  { path: '', component: FeatureComponent }
];

@NgModule({
  declarations: [FeatureComponent],
  imports: [
    CommonModule,
    RouterModule.forChild(featureRoutes)
  ]
})
export class FeatureModule { }
This is the FeatureModule that will be lazily loaded. It has its own routing configuration using the forChild method of the RouterModule to define the routes for the FeatureModule. This module declares the components that belong to this feature and imports RouterModule.forChild to define child routes specific to this module.