Creating multiple bundles using angular-cli webpack
If your splitting the areas that you want to be lazy loaded into separate modules, you should be able to produce multiple bundles. Take a look at this plnkr on routing and navigation taken directly from the angular.io website.
If you configure your routes this way you should be able to produce a build when running ng serve similar to:
Notice the chunk files. In my project, these chunk files get loaded asynchronously when navigating to the 'crisis' and 'heroes' routes.
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' }
];
It is the role of NgModule and RouterModule.forChild(). Here is a very good article for starting big Angular 2 modular aplications developpement : http://blog.angular-university.io/angular2-ngmodule/
The first thing that we need to do is to remove every mention of the Home component or the HomeModule from the App component and the main routing configuration:
We can see here that the App component no longer imports HomeModule, instead the routing config uses loadChildren to say that if /home or any other url starting with it gets hit, then the file home.module should be loaded via an Ajax call.
Shortly, to move some logic and components in a lazy module, you can run this command :
ng g module child --routing
Then angular-cli will generate a NgModule (app/child/child.module.ts
) and a child router configuration (app/child/child-routing.module.ts
).
The route for lazy loading this child router will be :
{ path: 'child', loadChildren: 'app/child/child.module#ChildModule' }
And finally move what you want in your ChildModule with one constraint : other module (as AppModule) will not be able to use any ChildModule dependency (like a service, for example). If you need it, a good practice is to create a shared module.