Search code examples
javascriptangularwebpackdynamic-loadingcode-splitting

Dynamically Load Modules with webpack and angular2


I have an angular2 app structure with 4 sub-apps that require some common configurations.These sub-apps are independent of each other. I am using webpack for dynamic loading and code splitting. Each sub-apps will have their own js files once they will be converted from .ts files. I want to bundle js files respective to the loading of sub-apps by the browser client.

E.g.
App-1 ===> app1.js

App-2 ===> app2.js

App-3 ===> app3.js

App-4 ===> app4.js

Now If browser client wants to load App-1 then only app1.js will bundled and sent to the client. This will improve app performance by not loading the unneccessary js modules.

Is there any way to acheive the same using webpack?

Thanks in advance.


Solution

  • Only modules can be lazy-loaded (on demand) by angular. Therefore you have to bundle on ore more components which should be loaded on demand (lazy-loaded) in a module.

    See here sample module:

    import { NgModule, Component} from '@angular/core';
    import { CommonModule }  from '@angular/common';
    import { Routes, RouterModule } from '@angular/router';
    
    import { Ng2BootstrapModule } from 'ng2-bootstrap/ng2-bootstrap';
    
    import { POIListeComponent }      from   './poiliste';
    
    
    const routes: Routes = [
        { path: '', component: POIListeComponent }
    ]
    
    
    @NgModule({
        imports: [CommonModule, Ng2BootstrapModule, RouterModule.forChild(routes)],
        declarations: [POIListeComponent]
    })
    
    export class myPOIListeModule { } 
    

    to make it lazy-loaded automatically you have to provide a route definition like this:

    export const AppRoutes: Routes = [
          {
            path:       'poiliste',
            loadChildren: () => System.import('./modules/poiliste/poiliste.module').then(m => m.POIListeModule)
        }
    ];
    

    That's all, at least when using webpack. When running your project (build) you can see then the "chunks" generated by webpack for each of the lazy-loaded modules then.