如何为新的Angular 4项目启用树抖动

Ric*_*ter 13 tree-shaking angular4 angular

我刚刚用CLI创建了一个新的Angular 4项目: ng new test

版本:

@angular/cli: 1.0.0
node: 6.10.0
os: win32 x64
@angular/common: 4.0.1
@angular/compiler: 4.0.1
@angular/core: 4.0.1
@angular/forms: 4.0.1
@angular/http: 4.0.1
@angular/platform-browser: 4.0.1
@angular/platform-browser-dynamic: 4.0.1
@angular/router: 4.0.1
@angular/cli: 1.0.0
@angular/compiler-cli: 4.0.1
Run Code Online (Sandbox Code Playgroud)

但是,由于我未使用的类FooBar仍在main.*.js文件中,因此树抖动无法正常工作.

我的示例组件TS文件(FooBar不应该在输出中):

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
}

export class FooBar {
  foo = "hello";
}
Run Code Online (Sandbox Code Playgroud)

我试图使用汇总(如文档中所述),但这不起作用......

有没有一种简单的方法来启用树木摇晃?(我希望在通过CLI创建项目时默认启用它).

更新:我正在使用ng build --prod它仍然没有被震动..

R. *_*rds 5

更新:从angular-cli Wiki

所有构建都利用捆绑和有限的树状摇动,而 --prod构建也通过UglifyJS运行有限的死代码消除。

也请参见下文。

提前(AOT)编译器

一个--prod构建默认为--aot=true现在; 它有一段时间了。

我在angular.io网站上没有找到任何文档,该文档提供了有关摇树的确切过程的大量详细信息。Angular CLI已经使用webpack已有一段时间了,这里有一些有关该工具如何摇树的信息UglifyJS似乎是一个常见的主题。

只要您遵循上面有关AOT的链接中的指南,您就可以获得良好的结果。如果您难以使用第三方库进行AOT编译,则始终存在未编写该库以支持AOT的风险。虽然,如今有望实现AOT兼容性。


och*_*obi 5

用于摇树ng build --prod --build-optimizer。这样 vendor.js 和 main.js 就合并在 main.js 文件中。为避免这种情况,您必须添加--vendor-chunk=true