简体   繁体   中英

Shared angular modules not landing in webpack common chunk

I have a lot of angular modules that are reused in the entire application, eg

  • I18nModule
  • StringInputModule
  • ...

After building the app via angular CLI and inspecting the bundle with webpack bundle analyzer, these shared modules pop up in different modules that include them. Is there a way to force them into the common chunk instead? Or what are possible mistakes that can result into this behaviour of code duplication instead of detecting that it is indeed a shared module.

To clarify: the common chunk exists, but only a handfull of ~ 50 shared modules are actually bundled within that chunk. The rest is either duplicated across different feature chunks or a lot of them are within the first feature page module.

AoT is enabled, so is the commonChunk option ( https://angular.io/cli/build )

You can create a sharedModule where all of your reusable component are and then import that module in appmodule of import sharedModule when ever you need those Ex:

$ng gm shared --routing

$ ng g c shared/components/shared --module shared

shared.module.ts

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";

import { SharedRoutingModule } from "./shared-routing.module";
import { SharedComponent } from "./components/shared/shared.component";

@NgModule({
  declarations: [SharedComponent],
  imports: [CommonModule, SharedRoutingModule],
  exports: [SharedComponent]
})
export class SharedModule {}

app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { SharedModule } from "./shared/shared.module";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, SharedModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

first.module.ts

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";

import { ExampleRoutingModule } from "./example-routing.module";
import { ExampleComponent } from "./components/example/example.component";
import { SharedModule } from "../shared/shared.module";

@NgModule({
  declarations: [ExampleComponent],
  imports: [CommonModule, ExampleRoutingModule, SharedModule]
})
export class ExampleModule {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM