Kanishk Agrawal Blog

    Ahead of Time (AOT) Compilation in Angular

    July 10, 2016

    Ever happened that your Angular code runs perfectly in your local machine and fails in build for deployment. Well, if yes then this post will help you out to avoid unexpected ERROR while prod build.

    Angular Compilation

    Angular offers two types of compilation.

    1. Just in Time (JIT) compilation

    JIT compilation is the default when you run the build-only or the build-and-serve-locally CLI commands.

    ng serve
    ng build
    1. Ahead of Time (AOT) compilation

    For AOT compilation appending - -aot flag is required.

    ng serve --aot
    ng build --aot

    Why Angular needs Compilation?

    As Angular offers HTML templates and components with it which are not understood by the browsers directly. So , any of the above two type of compilation is required before they can run in a browser.

    What different does AOT do?

    During the build phase and before the browsers runs and downloads the code, the ‘HTML and Typescript’ code compiles into Javascript code. Compiling during build process ensures a faster rendering into the browser.

    Let us see for the same piece of code how JIT and AOT compilation could make a difference.

    ng serve

    IMAGE

    ng serve --aot

    IMAGE

    Clearly, ahead-of-time compilation could foresee the error failures that may occur ahead of time.

    Why AOT?

    • Faster Rendering
    • Reduce Angular Payload
    • Detect template errors earlier
    • Less injection attacks chances
    • Less Async HTTP requests

    As Angular offers JIT compilation by default, therefore AOT compilation is recommended for above reason before building your code for deployment. AOT compilation performs more build restrictions and code optimisations compared to JIT compilation.


    Kanishk Agrawal

    Written by Kanishk Agrawal who lives and works in Bangalore, India.