What is an ahead-of-time compilation in Angular?

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.

Why should we use ahead-of-time compiler?

Below are a few reasons why we should start using AOT compilation:

  • Fast rendering: Because of AOT compilation, the browser doesn’t have to waste time compiling the Angular code during runtime, ensuring fast component rendering.
  • One-time compilation process: The compilation is a one-time process in the AOT compiler that happens while building the project.
  • Reduced application size: AOT compiler can reduce the application size because there is no need to download the Angular compiler.
  • Early bug detection: As AOT compilation is performed during build time, it can detect template binding errors easily before users can see them.

Note: Ahead-of-time compiler is set as the default compiler for Angular 9 and higher versions.

Working of the AOT compiler

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.

Code example

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;
}

Code explanation

  • Line 3: The @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.
  • Line 10: The 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

Copyright ©2024 Educative, Inc. All rights reserved