首页 > 解决方案 > 共享的角度模块未登陆 webpack 公共块

问题描述

我有很多在整个应用程序中重用的角度模块,例如

在通过 Angular CLI 构建应用程序并使用 webpack 包分析器检查包后,这些共享模块会在包含它们的不同模块中弹出。有没有办法强迫它们进入common块?或者有哪些可能的错误会导致这种代码重复行为,而不是检测到它确实是一个共享模块。

澄清一下:公共块存在,但实际上只有少数约 50 个共享模块捆绑在该块中。其余的要么在不同的功能块中重复,要么很多都在第一个功能页面模块中。

AoT 已启用,commonChunk选项也已启用(https://angular.io/cli/build

标签: angularwebpackangular-clicode-splitting

解决方案


您可以在所有可重用组件所在的位置创建一个 sharedModule,然后在需要时将该模块导入 import sharedModule 的 appmodule 中:

$ng gm 共享--路由

$ ng gc shared/components/shared --module 共享

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 {}

推荐阅读