我爱编程

Angular X AOT + Rollup的那些坑

2017-08-16  本文已影响170人  渡笃狼

Pitfalls

reflect-metadata shim is required when using class decorators

Solution from Stackoverflow:
These two are needed to be imported on the typescript file, they are required since we are using the ng directives.
I think you are missing only the following, which needs to be at the beginning of your top level typescript or JavaScript file. Specifically, these need to be prior to the first line is that loads Angular.

import 'zone.js';
import 'reflect-metadata';

把上述代码加到 main-aot.ts, 虽然解决了angular X loading的问题,但会出现如下错误:

Uncaught ReferenceError: require is not defined
build.js:1
build.js:1

这是因为rollup没法处理这种import, 改用<script>引入zone和reflect到index.html中

index-aot.jpg

Angular的编译器能够在运行时调用(例如,用户在浏览的时候) 或构建时调用(作为构建过程的一部分)。 这是因为Angular的可移植性 - 我们可以在任何JavaScript VM的平台上运行Angular框架,所以这就是为什么要让Angular编译器能在浏览器和node环境中运行

事件流和即时编译(Just-in-time)

事件流与预编译

相比之下,AoT需要通过以下步骤:

虽然上述过程似乎更为复杂,用户只需通过步骤:

因为AOT采用code generation方式,生成的代码量会比原来的文件大,应用足够大时,AOT的大小会反超JIT, 不过可以缩短启动时间

Reference: https://coyee.com/article/11723-ahead-of-time-compilation-in-angular

angular-cli ng build --prod: 1.5MB, 869ms
console errors:
404 bootstrap.css, common.css, style.css, mock-config.json, mock-catalog.json

ngc + rollup: 1.1MB, 649ms

可继续优化的点:minify? gzip, lazy loading

gzip是在web server上配置的,等到deploy的时候再作讨论
lazy loading目前rollup bundler不支持,但了解到webpack支持,angular-cli里面用的就是webpack的tree-shaking。
rollup和webpack都是支持tree-shaking的bundler, 但是webpack对tree-shaking的支持没有rollup好。

会持续更新后续的bundler选择问题~~~

滚来更新后续了!!!
没想到最后用的竟然是angular-cli自带的ng build -prod,原因是:这样打出来的包和手工aot打出来的包差别不大,不管是从文件大小还是运行速度。。。

上一篇下一篇

猜你喜欢

热点阅读