Member-only story
A Brief Intro to Ahead-of-Time (AOT) Compilation in Angular
The ins and outs of AOT compilation
Introduction
Angular code is mainly made up of HTML templates and TypeScript components, but for Angular applications to run in the browser, they have to be compiled to JavaScript code.
There are two main ways of compiling Angular code to JavaScript.
- Just-in-time (JIT) compilation — This is when the code is compiled in the browser at runtime.
- Ahead-of-time (AOT) compilation — This is when the code is compiled as part of the build process, hence the name ahead-of-time.
Starting with Angular version 9, the default compilation of choice is AOT. This means that whenever you build your Angular application for production with the command ng build --prod
, the application will also be compiled as part of the build process.
Note: For Angular version 8 and older, to compile using AOT, use the command ng build --prod --aot=true
.
Advantages of AOT compilation
At this stage, you might be wondering what AOT has to offer. Below are some advantages of AOT compilation over JIT compilation.
- Faster rendering of your Angular application — With AOT, the code is compiled during the build process. Therefore, the browser loads executable code that is ready to be rendered immediately. Very fast!
- Smaller Angular application size — There is no need to download the Angular compiler since the application is already compiled. If the compilation is to happen in the browser at runtime like in JIT, the Angular application is shipped together with an Angular compiler. The compiler is roughly half the size of Angular itself. Pretty heavy right?
- Better code quality — This is because template errors are detected early as the application compiles as part of the build process.
- More secure and robust applications — That’s because the HTML templates and TypeScript components are not evaluated dynamically at runtime in the browser. This leads to fewer opportunities for injection attacks.