Blog>
Snippets

Micro-Frontend Routing and Lazy Loading

Demonstrate setting up Angular routing for a micro-frontend architecture that supports lazy loading of modules only when they're required.
const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule)
  },
  {
    path: 'settings',
    loadChildren: () => import('./settings/settings.module').then(m => m.SettingsModule)
  },
  // add more routes here
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
This code defines the route configuration for an Angular application, specifying that certain paths ('dashboard', 'settings', etc.) should lazily load their respective feature modules only when those paths are navigated to. This helps in splitting the build into smaller chunks and only loading the necessary code when required, reducing the initial load time.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule // Import AppRoutingModule to use the routes
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
This code sets up the main Angular module for the application, 'AppModule'. It imports the BrowserModule and the AppRoutingModule that contains the lazy-loaded routes. The main component, 'AppComponent', is declared and bootstrapped here. This is the root module configuration that glues everything together.