Browsers cannot comprehend Angular directly. As the Angular project consists of several HTML templates, the browser must download the code first and compile it before running. It is where ahead-of-time or AOT compilation is used. AOT compiler converts the high-level typescript and HTML into the machine-level Javascript code. The browser gets the precompiled code that makes the rendering and execution easier.
Below are a few reasons why we should start using AOT compilation:
Note: Ahead-of-time compiler is set as the default compiler for Angular 9 and higher versions.
The ahead-of-time compilation works in three phases, as shown below:
AOT functions extract the metadata from the Angular application. The metadata can be defined in the form of decorators such as @Component
, @Input
, and @Output
. AOT performs the template type checking and code generation based on metadata extracted in the first phase, code Analysis. The metadata tells the AOT compiler how to deal with Angular components during runtime.
Let's dive into the example below to see the metadata definition and working of a compiler:
import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { title = "App"; isDisabled: boolean = false; }
@Component
decorator in app.component.ts
is the metadata object that defines the way AppComponent
instance is created. AOT compiler generates a factory of AppComponent
based on metadata extracted during the code analysis phase.isDiabled
is the boolean property that is used in app.component.html
file. AOT compiler will check for the template type and mark it ready for the browser.Free Resources