Angular 角度AOT编译应用程序未按预期进行树抖动

Angular 角度AOT编译应用程序未按预期进行树抖动,angular,angular-cli,angular2-aot,tree-shaking,angular-aot,Angular,Angular Cli,Angular2 Aot,Tree Shaking,Angular Aot,我有一个模块(MyCommonModule),其中包含我计划在不同应用程序之间共享的通用组件、服务等 这是一个简单应用程序的示例,它只导入MyCommonModule(但尚未在AppComponent中引用任何组件): 模块的定义如下: import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; // Components impor

我有一个模块(
MyCommonModule
),其中包含我计划在不同应用程序之间共享的通用组件、服务等

这是一个简单应用程序的示例,它只导入
MyCommonModule
(但尚未在
AppComponent
中引用任何组件):

模块
的定义如下:

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
            ]
        };
    }
}
当我运行
ngbuild--environment=prod--target=production
时,我得到的构建是AOT:d。如果我使用
源地图资源管理器
分析输出,我可以看到生成的
main.*.bundle.js
vendor.*.bundle.js
包含
MyCommonModule
中的所有服务和组件(及其引用),即使我在我的应用程序中没有使用它


这是预期的行为吗?是否为angular cli应用程序启用了树抖动功能?

“树抖动器”从上到下遍历依赖关系图,并像树中的枯叶一样抖掉未使用的代码。如果您的AppModule导入MyCommonModule,“树摇器”无法知道您是否实际使用了它(就您使用的JavaScript代码而言)

此外,解决问题后,请尝试以下操作:

ng build -prod --build-optimizer=true

(还不能添加评论,但这可能会有帮助)

您确实在应用程序中使用了它-您正在将
MyCommonModule
导入
AppModule
,并且
MyCommonModule
导入您的所有服务和组件。如果我的理解是正确的,树震动在ES6模块级别上有效,而不是角度级别-如果你在某处导入一个模块,它不会被震出。只有代码中没有导入的东西才会被删除。
ng build -prod --build-optimizer=true