美文网首页我爱编程
Angular X AOT + Rollup的那些坑

Angular X AOT + Rollup的那些坑

作者: 渡笃狼 | 来源:发表于2017-08-16 23:59 被阅读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)

    • 使用TypeScript开发Angular应用。

    • 使用tsc编译应用。

    • 构建。

    • 压缩。

    • 部署。
      一旦我们部署了应用程序,用户打开浏览器,将经历以下步骤 (没有严格的CSP):

    • 下载所有JavaScript资源。

    • Angular 启动。

    • Angular通过JIT编译处理过程,例如对我们的应用程序的每一个ie组件生成对应的javascript代码。

    • 应用页面呈现。

    事件流与预编译

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

    • 使用Typescript开发Angular 应用。
    • 使用 ngc来编译应用。
    • 执行Angular的编译器编译模板和生成(通常是)TypeScript文件。
    • 编译TypeScript文件为JavaScript代码。
    • 捆绑。
    • 压缩。
    • 部署。

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

    • 下载所有的资源。
    • Angular启动。
    • 应用程序被渲染。

    因为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打出来的包差别不大,不管是从文件大小还是运行速度。。。

    相关文章

      网友评论

        本文标题:Angular X AOT + Rollup的那些坑

        本文链接:https://www.haomeiwen.com/subject/xttirxtx.html