Lazy Loading Modules in Angular with Pre-rendering
Illustrate the implementation of lazy loading modules in Angular Universal, preserving the SEO benefits of pre-rendering while boosting performance.
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./features/feature.module').then(m => m.FeatureModule)
}
// other routes...
];
Define the route for a lazy-loaded module in the Angular routing configuration. Here, 'feature' is the path, and 'FeatureModule' is the feature module to be lazy-loaded.
@NgModule({
imports: [RouterModule.forRoot(routes)]
// other imports and metadata...
})
export class AppRoutingModule { }
The root routing module where the routes are registered, including the lazy-loaded route.
@NgModule({
// declarations and providers...
imports: [
CommonModule,
RouterModule.forChild(featureRoutes)
]
})
export class FeatureModule { }
The lazy-loaded feature module itself. It imports 'RouterModule.forChild()' with its own child routes.
server.ts
// Setup the server...
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
app.get('*', (req, res) => {
res.render('index', { req });
});
Server configuration for Angular Universal. Static files are served directly, while all other requests render through Angular Universal, preserving SEO benefits.
npm install @nguniversal/express-engine --save
Install the necessary package to enable Angular Universal express engine which allows server-side rendering.
npm run build:ssr && npm run serve:ssr
Build and serve the Angular app with server-side rendering enabled for pre-rendering content for SEO purposes while having lazy-loaded modules.