Reputation: 8938
I have a module (MyCommonModule
) with common components, services, etc that I plan to share between different angular applications.
This is an example of a simple app, that only imports MyCommonModule
(but doesn't reference any of it in AppComponent
yet):
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyCommonModule } from "../common";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
MyCommonModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
MyCommonModule
is defined like this:
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
// Components
import { SomeComponent } from "./components/some.component";
export * from "./components/some.component";
// Directives
import { SomeDirective } from "./directives/some.directive";
export * from "./directives/some.directive";
// Services
import { SomeService } from "./services/some.service";
export * from "./services/some.service";
// Models
export * from "./models/some.model";
@NgModule({
imports: [
CommonModule
],
declarations: [
SomeComponent,
SomeDirective
],
providers: [],
exports: [
SomeComponent,
SomeDirective
]
})
export class MyCommonModule {
public static forRoot(): ModuleWithProviders {
return {
ngModule: MyCommonModule,
providers: [
SomeService
]
};
}
}
When I run ng build --environment=prod --target=production
I get a build that is AOT:d. If I analyze the output using source-map-explorer
I can see that the resulting main.*.bundle.js
and vendor.*.bundle.js
contains all the services and components (and their references) in MyCommonModule
, even though I didn't use any of it in my app.
Is that the expected behavior? Is tree shaking even enabled for angular cli apps?
Upvotes: 0
Views: 604
Reputation: 11
Additionally give the following a try once you solved your problem:
ng build -prod --build-optimizer=true
(can't add comments yet, but that might be helpful)
Upvotes: 0
Reputation: 1346
"tree shaker" walks the dependency graph, top to bottom, and shakes out unused code like dead leaves in a tree. If your AppModule imports MyCommonModule the "tree shaker" can't know if you actually use it (In terms of JavaScript you use that code)
Upvotes: 1