Lazy Loading Modules With Angular 2 And Webpack

I’m sure this is obvious to some people, but this issue threw me for a loop.

When building applications in Angular 2, it’s best practice to divide up your application into feature modules. This keeps your code simple and easy to work with. You can lazy load these child modules to improve initial load times and keep people from downloading code for areas they don’t have access to.

The Angular 2 website has excellent tutorials on how to set this up, but if you’re using Webpack, those instructions (link) don’t quite work.

Here’s the code from the Angular 2 website.

export const routes: Routes = [
  { path: '', redirectTo: 'contact', pathMatch: 'full'},
  { path: 'crisis', loadChildren: 'app/crisis/crisis.module#CrisisModule' },
  { path: 'heroes', loadChildren: 'app/hero/hero.module#HeroModule' }
];

You could assume that this code isn’t specific to using system.js as your module loader, but you’d be wrong. Webpack, by default, chokes on these lazy loaded modules. I spent more time than I’m willing to admit trying to figure out the arcane errors before I realized that the Webpack was the problem. Fortunately, this problem is easy to fix.

Like everything else in Webpack, there’s a loader for that. In this case, you want the Angular 2 Router Loader (more info here). Be attentive to the instructions, because the module strings work different than they do with system.js. For example, the Webpack loader supports relative paths. (The Angular 2 docs say otherwise) Once you setup the loader, lazy loading in Webpack works like a champ.

About the Author Dustin Ewers

follow me on:

Leave a Comment: