【问题标题】:Angular AOT compiled app not tree shaking as expectedAngular AOT 编译的应用程序没有按预期摇树
【发布时间】:2017-11-30 08:36:54
【问题描述】:

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

这是一个简单应用的示例,它只导入MyCommonModule(但在AppComponent 中还没有引用它):

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 是这样定义的:

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
            ]
        };
    }
}

当我运行 ng build --environment=prod --target=production 时,我得到了一个 AOT:d 的构建。如果我使用source-map-explorer 分析输出,我可以看到生成的main.*.bundle.js 和vendor.*.bundle.js 包含MyCommonModule 中的所有服务和组件(及其引用),即使我没有在我的应用程序。

这是预期的行为吗?是否为 Angular cli 应用程序启用了摇树?

【问题讨论】:

  • 你确实在你的应用程序中使用了它——你将MyCommonModule导入AppModule,MyCommonModule导入你所有的服务和组件。如果我的理解是正确的,那么摇树在 ES6 模块级别上起作用,而不是在 Angular 级别上——如果你在某个地方导入一个模块,它就不会被摇晃出来。只有未在代码中任何地方导入的内容才会被删除。

标签: angular angular-cli angular2-aot tree-shaking angular-aot


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    解决问题后,请尝试以下方法:

    ng build -prod --build-optimizer=true
    

    (还不能添加 cmets,但这可能会有所帮助)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-14
      • 2019-10-23
      • 2016-11-14
      • 2017-03-10
      • 2020-09-04
      • 2018-02-14
      • 2013-08-09
      • 2018-11-24
      相关资源
      最近更新 更多