Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share an external module between lazy loaded modules in angular2

My app has components that use a heavy-weight external package (ag-grid, about 1MB) that is provided as an angular2 module (AgGridModule). I would like to load this package only when the components using it are required, so my ContentModule and all of its submodules are lazy-loaded. The whole structure looks like this:

enter image description here

However, when I import AgGridModule into both Submodule1 and Submodule3, it ends up being included in compiled JS twice, making both 1.chunk.js and 3.chunk.js large. I tried importing it into ContentModule, but then the submodules do not recognize the components that are included in AgGridModule, even if I list them in the exports property of ContentModule.

@NgModule({
  imports: [
    ContentRoutingModule,
    SomeOtherModule,
    AgGridModule.withComponents([])
  ],
  exports: [
    // this is the component from AgGridModule that I use
    AgGridNg2
  ]
})
export class ContentModule { }

Is there a way to share a module between lazy loaded modules, or to expose some components of an imported module to lazy loaded children?

UPD: Creating a shared module and importing it into submodules does not help, there are still two chunks with about 1MB each: enter image description here

UPD2: I solved the problem temporarily by merging Submodule1 and Submodule3 into a single module.

like image 915
Anton Poznyakovskiy Avatar asked Jan 24 '17 11:01

Anton Poznyakovskiy


People also ask

How do I pass data from one module to another in Angular 8?

You can import MemberCardModule into AppModule directly. Or import into ShareModule and import ShareModule into AppModule. It is important to import Modules into AppModule. And then you can you MemberCardModule.

Can we have multiple NgModule in Angular?

Yes you can split your application into modules.


1 Answers

You need to create a SharedAgGridModule:

@NgModule({
  imports: [
    AgGridModule.withComponents([])
  ],
  exports: [
    ContentModule,
    AgGridModule
  ]
})
export class SharedAgGridModule{}

Then you should import this module just for the submodules which uses AgGrid. No need to also import the ContentModule in those submodules, because it is exported in this module

like image 64
Poul Kruijt Avatar answered Sep 19 '22 08:09

Poul Kruijt