anoop-khandelwal
anoop-khandelwal

Reputation: 3860

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.

Upvotes: 1

Views: 1591

Answers (2)

Dotan Langsam
Dotan Langsam

Reputation: 29

You need to split your code into different bundles by creating an entry in webpack configuration for each AppModule. Then you can load then dynamically when routing to them with loadChildren.

Here's how to create a new entry: How do I do code splitting with webpack on angular 2 app?

And here's how to dynamically load your module: https://angular-2-training-book.rangle.io/handout/modules/lazy-loading-module.html

Hope this was what you meant

Upvotes: 0

Karl
Karl

Reputation: 3099

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.

Upvotes: 1

Related Questions