The Ahead-of-Time (AOT) Compiler: Angular Compilation
The Ahead-of-Time (AOT) Compiler: Angular Compilation
The Angular Ahead-of-Time (AOT) compiler converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and
runs that code.
This guide explains how to build with the AOT compiler and how to write Angular metadata that AOT can compile.
Watch compiler author Tobias Bosch explain the Angular Compiler at AngularConnect 2016.
{@a overview}
Angular compilation
An Angular application consists largely of components and their HTML templates. Before the browser can render the application, the components and templates must be converted to
executable JavaScript by an Angular compiler.
JIT compilation is the default when you run the build-only or the build-and-serve-locally CLI commands:
ng build ng serve
{@a compile}
For AOT compilation, append the --aot flags to the build-only or the build-and-serve-locally CLI commands:
The `--prod` meta-flag compiles with AOT by default. See the [CLI documentation](https://github.com/angular/angular-cli/wiki) for details, especially the [`build` topic]
(https://github.com/angular/angular-cli/wiki/build).
{@a why-aot}
With AOT, the browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application immediately, without waiting to compile
the app first.
The compiler inlines external HTML templates and CSS style sheets within the application JavaScript, eliminating separate ajax requests for those source files.
There's no need to download the Angular compiler if the app is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.
The AOT compiler detects and reports template binding errors during the build step before users can see them.
Better security
AOT compiles HTML templates and components into JavaScript files long before they are served to the client. With no templates to read and no risky client-side HTML or JavaScript
evaluation, there are fewer opportunities for injection attacks.
Angular metadata tells Angular how to construct instances of your application classes and interact with them at runtime.
You specify the metadata with decorators such as @Component() and @Input() . You also specify metadata implicitly in the constructor declarations of these decorated classes.
In the following example, the @Component() metadata object and the class constructor tell Angular how to create and display an instance of TypicalComponent .
@Component({
selector: 'app-typical',
template: '<div>A typical component for {{data.name}}</div>'
)}
export class TypicalComponent {
@Input() data: TypicalData;
constructor(private someService: SomeService) { ... }
}
The Angular compiler extracts the metadata once and generates a factory for TypicalComponent . When it needs to create a TypicalComponent instance, Angular calls the
factory, which produces a new visual element, bound to a new instance of the component class with its injected dependency.
Metadata restrictions
You write metadata in a subset of TypeScript that must conform to the following general constraints:
Phase 1: analysis
The TypeScript compiler does some of the analytic work of the first phase. It emits the .d.ts type definition files with type information that the AOT compiler needs to generate
application code.
At the same time, the AOT collector analyzes the metadata recorded in the Angular decorators and outputs metadata information in .metadata.json files, one per .d.ts file.
You can think of .metadata.json as a diagram of the overall structure of a decorator's metadata, represented as an abstract syntax tree (AST).
{@a expression-syntax}
Expression syntax
The collector only understands a subset of JavaScript. Define metadata objects with the following limited syntax:
Syntax Example
Calls bake(ingredients)
Conditional operator a ? b : c
Parentheses (a + b)
If an expression uses unsupported syntax, the collector writes an error node to the .metadata.json file. The compiler later reports the error if it needs that piece of metadata to
generate the application code.
If you want `ngc` to report syntax errors immediately rather than produce a `.metadata.json` file with errors, set the `strictMetadataEmit` option in `tsconfig`. ``` "angularCompilerOptions":
{ ... "strictMetadataEmit" : true } ``` Angular libraries have this option to ensure that all Angular `.metadata.json` files are clean and it is a best practice to do the same when building your
own libraries.
No arrow functions
The AOT compiler does not support function expressions and arrow functions, also called lambda functions.
@Component({
...
providers: [{provide: server, useFactory: () => new Server()}]
})
The AOT collector does not support the arrow function, () => new Server() , in a metadata expression. It generates an error node in place of the function.
When the compiler later interprets this node, it reports an error that invites you to turn the arrow function into an exported function.
@Component({
...
providers: [{provide: server, useFactory: serverFactory}]
})
Beginning in version 5, the compiler automatically performs this rewritting while emitting the .js file.
Limited function calls
The collector can represent a function call or object creation with new as long as the syntax is valid. The collector only cares about proper syntax.
But beware. The compiler may later refuse to generate a call to a particular function or creation of a particular object. The compiler only supports calls to a small set of functions and will
use new for only a few designated classes. These functions and classes are in a table of below.
Folding
{@a exported-symbols} The compiler can only resolve references to exported symbols. Fortunately, the collector enables limited use of non-exported symbols through folding.
The collector may be able to evaluate an expression during collection and record the result in the .metadata.json instead of the original expression.
For example, the collector can evaluate the expression 1 + 2 + 3 + 4 and replace it with the result, 10 .
This process is called folding. An expression that can be reduced in this manner is foldable.
{@a var-declaration} The collector can evaluate references to module-local const declarations and initialized var and let declarations, effectively removing them from the
.metadata.json file.
@Component({
selector: 'app-hero',
template: template
})
export class HeroComponent {
@Input() hero: Hero;
}
The compiler could not refer to the template constant because it isn't exported.
But the collector can fold the template constant into the metadata definition by inlining its contents. The effect is the same as if you had written:
@Component({
selector: 'app-hero',
template: '<div>{{hero.name}}</div>'
})
export class HeroComponent {
@Input() hero: Hero;
}
There is no longer a reference to template and, therefore, nothing to trouble the compiler when it later interprets the collector's output in .metadata.json .
You can take this example a step further by including the template constant in another expression:
@Component({
selector: 'app-hero',
template: template + '<div>{{hero.title}}</div>'
})
export class HeroComponent {
@Input() hero: Hero;
}
'<div>{{hero.name}}</div><div>{{hero.title}}</div>' .
Foldable syntax
The following table describes which expressions the collector can and cannot fold:
Syntax Foldable
Calls no
New no
Supported binary operator yes, if both left and right are foldable
If an expression is not foldable, the collector writes it to .metadata.json as an AST for the compiler to resolve.
It's the compiler's job to interpret the .metadata.json in the code generation phase.
The compiler understands all syntax forms that the collector supports, but it may reject syntactically correct metadata if the semantics violate compiler rules.
Decorated component class members must be public. You cannot make an @Input() property private or internal.
{@a supported-functions} Most importantly, the compiler only generates code to create instances of certain classes, support certain decorators, and call certain functions from the
following lists.
New instances
The compiler only allows metadata that create instances of the class InjectionToken from @angular/core .
Annotations/Decorators
The compiler only supports metadata for these Angular decorators.
Decorator Module
Attribute @angular/core
Component @angular/core
ContentChild @angular/core
ContentChildren @angular/core
Directive @angular/core
Host @angular/core
HostBinding @angular/core
HostListener @angular/core
Inject @angular/core
Injectable @angular/core
Input @angular/core
NgModule @angular/core
Optional @angular/core
Output @angular/core
Pipe @angular/core
Self @angular/core
SkipSelf @angular/core
ViewChild @angular/core
The compiler also supports macros in the form of functions or static methods that return an expression.
You can call the wrapInArray in a metadata definition because it returns the value of an expression that conforms to the compiler's restrictive JavaScript subset.
@NgModule({
declarations: wrapInArray(TypicalComponent)
})
export class TypicalModule {}
@NgModule({
declarations: [TypicalComponent]
})
export class TypicalModule {}
The collector is simplistic in its determination of what qualifies as a macro function; it can only contain a single return statement.
The Angular RouterModule exports two macro static methods, forRoot and forChild , to help declare root and child routes. Review the source code for these methods to
see how macros can simplify configuration of complex NgModules.
Metadata rewriting
The compiler treats object literals containing the fields useClass , useValue , useFactory , and data specially. The compiler converts the expression initializing one of these
fields into an exported variable, which replaces the expression. This process of rewriting these expressions removes all the restrictions on what can be in them because the compiler
doesn't need to know the expression's value—it just needs to be able to generate a reference to the value.
class TypicalServer {
@NgModule({
providers: [{provide: SERVER, useFactory: () => TypicalServer}]
})
export class TypicalModule {}
Without rewriting, this would be invalid because lambdas are not supported and TypicalServer is not exported.
class TypicalServer {
@NgModule({
providers: [{provide: SERVER, useFactory: ɵ0}]
})
export class TypicalModule {}
This allows the compiler to generate a reference to ɵ0 in the factory without having to know what the value of ɵ0 contains.
The compiler does the rewriting during the emit of the .js file. This doesn't rewrite the .d.ts file, however, so TypeScript doesn't recognize it as being an export. Thus, it does not
pollute the ES module's exported API.
Metadata Errors
The following are metadata errors you may encounter, with explanations and suggested corrections.
The compiler encountered an expression it didn't understand while evalutating Angular metadata.
Language features outside of the compiler's restricted expression syntax can produce this error, as seen in the following example:
// ERROR
export class Fooish { ... }
...
const prop = typeof Fooish; // typeof is not valid in metadata
...
// bracket notation is not valid in metadata
{ provide: 'token', useValue: { [prop]: 'value' } };
...
You can use typeof and bracket notation in normal application code. You just can't use those features within expressions that define Angular metadata.
Avoid this error by sticking to the compiler's restricted expression syntax when writing Angular metadata and be wary of new or unusual TypeScript features.
{@a reference-to-a-local-symbol}
_Reference to a local (non-exported) symbol 'symbol name'. Consider exporting the symbol._
The compiler encountered a referenced to a locally defined symbol that either wasn't exported or wasn't initialized.
// ERROR
let foo: number; // neither exported nor initialized
@Component({
selector: 'my-component',
template: ... ,
providers: [
{ provide: Foo, useValue: foo }
]
})
export class MyComponent {}
The compiler generates the component factory, which includes the useValue provider code, in a separate module. That factory module can't reach back to this source module to
access the local (non-exported) foo variable.
The compiler will fold the expression into the provider as if you had written this.
providers: [
{ provide: Foo, useValue: 42 }
]
Alternatively, you can fix it by exporting foo with the expectation that foo will be assigned at runtime when you actually know its value.
// CORRECTED
export let foo: number; // exported
@Component({
selector: 'my-component',
template: ... ,
providers: [
{ provide: Foo, useValue: foo }
]
})
export class MyComponent {}
Adding export often works for variables referenced in metadata such as providers and animations because the compiler can generate references to the exported variables
in these expressions. It doesn't need the values of those variables.
Adding export doesn't work when the compiler needs the actual value in order to generate code. For example, it doesn't work for the template property.
// ERROR
export let someTemplate: string; // exported but not initialized
@Component({
selector: 'my-component',
template: someTemplate
})
export class MyComponent {}
The compiler needs the value of the template property right now to generate the component factory. The variable reference alone is insufficient. Prefixing the declaration with
export merely produces a new error, " Only initialized variables and constants can be referenced ".
{@a only-initialized-variables}
_Only initialized variables and constants can be referenced because the value of this variable is needed by the template compiler._
The compiler found a reference to an exported variable or static field that wasn't initialized. It needs the value of that variable to generate code.
The following example tries to set the component's template property to the value of the exported someTemplate variable which is declared but unassigned.
// ERROR
export let someTemplate: string;
@Component({
selector: 'my-component',
template: someTemplate
})
export class MyComponent {}
You'd also get this error if you imported someTemplate from some other module and neglected to initialize it there.
@Component({
selector: 'my-component',
template: someTemplate
})
export class MyComponent {}
The compiler cannot wait until runtime to get the template information. It must statically derive the value of the someTemplate variable from the source code so that it can generate
the component factory, which includes instructions for building the element based on the template.
To correct this error, provide the initial value of the variable in an initializer clause on the same line.
// CORRECTED
export let someTemplate = '<h1>Greetings from Angular</h1>';
@Component({
selector: 'my-component',
template: someTemplate
})
export class MyComponent {}
For example, you may have defined a class and used it as an injection token in a providers array but neglected to export that class.
// ERROR
abstract class MyStrategy { }
...
providers: [
{ provide: MyStrategy, useValue: ... }
]
...
Angular generates a class factory in a separate module and that factory can only access exported classes. To correct this error, export the referenced class.
// CORRECTED
export abstract class MyStrategy { }
...
providers: [
{ provide: MyStrategy, useValue: ... }
]
...
For example, you may have set a providers useFactory property to a locally defined function that you neglected to export.
// ERROR
function myStrategy() { ... }
...
providers: [
{ provide: MyStrategy, useFactory: myStrategy }
]
...
Angular generates a class factory in a separate module and that factory can only access exported functions. To correct this error, export the function.
// CORRECTED
export function myStrategy() { ... }
...
providers: [
{ provide: MyStrategy, useFactory: myStrategy }
]
...
{@a function-calls-not-supported}
_Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function._
The compiler does not currently support function expressions or lambda functions. For example, you cannot set a provider's useFactory to an anonymous function or arrow function
like this.
// ERROR
...
providers: [
{ provide: MyStrategy, useFactory: function() { ... } },
{ provide: OtherStrategy, useFactory: () => { ... } }
]
...
You also get this error if you call a function or method in a provider's useValue . ``` // ERROR import { calculateValue } from './utilities';
To correct this error, export a function from the module and refer to the function in a useFactory provider instead.
export function myStrategy() { ... } export function otherStrategy() { ... } export function someValueFactory() { return calculateValue(); } ... providers: [ { provide: MyStrategy, useFactory:
myStrategy }, { provide: OtherStrategy, useFactory: otherStrategy }, { provide: SomeValue, useFactory: someValueFactory } ] ...
{@a destructured-variable-not-supported}
// destructured assignment to foo and bar const {foo, bar} = configuration; ... providers: [ {provide: Foo, useValue: foo}, {provide: Bar, useValue: bar}, ] ...
// CORRECTED import { configuration } from './configuration'; ... providers: [ {provide: Foo, useValue: configuration.foo}, {provide: Bar, useValue: configuration.bar}, ] ...
The compiler encountered a type and can't determine which module exports that type.
This can happen if you refer to an ambient type. For example, the Window type is an ambiant type declared in the global .d.ts file.
You'll get an error if you reference it in the component constructor, which the compiler must statically analyze.
// ERROR
@Component({ })
export class MyComponent {
constructor (private win: Window) { ... }
}
TypeScript understands ambiant types so you don't import them. The Angular compiler does not understand a type that you neglect to export or import.
In this case, the compiler doesn't understand how to inject something with the Window token.
If you must inject an instance of an ambiant type, you can finesse the problem in four steps:
export const WINDOW = new InjectionToken('Window'); export function _window() { return window; }
@Component({ ... providers: [ { provide: WINDOW, useFactory: _window } ] }) export class MyComponent { constructor (@Inject(WINDOW) private win: Window) { ... } }
The Window type in the constructor is no longer a problem for the compiler because it uses the @Inject(WINDOW) to generate the injection code.
Angular does something similar with the DOCUMENT token so you can inject the browser's document object (or an abstraction of it, depending upon the platform in which the
application runs).
@Component({ ... }) export class MyComponent { constructor (@Inject(DOCUMENT) private doc: Document) { ... } }
Name expected
The compiler expected a name in an expression it was evaluating. This can happen if you use a number as a property name as in the following example.
// ERROR
provider: [{ provide: Foo, useValue: { 0: 'test' } }]
Angular couldn't determine the value of the enum member that you referenced in metadata.
The compiler can understand simple enum values but not complex values such as those derived from computed properties.
... providers: [ { provide: BaseColor, useValue: Colors.White } // ok { provide: DangerColor, useValue: Colors.Red } // ok { provide: StrongColor, useValue: Colors.Blue } // bad ] ...
{@a tagged-template-expressions-not-supported}
The compiler encountered a JavaScript ES2015 tagged template expression such as,
// ERROR const expression = 'funky'; const raw = String.raw`A tagged template ${expression} string`; ... template: '<div>' + raw + '</div>' .
String.raw() is a tag function native to JavaScript ES2015.
The AOT compiler does not support tagged template expressions; avoid them in metadata expressions.
The compiler expected a reference to a symbol at the location specified in the error message.
This error can occur if you use an expression in the extends clause of a class.
Summary
What the AOT compiler does and why it is important.
Why metadata must be written in a subset of JavaScript.
What that subset is.
Other restrictions on metadata definition.
Macro-functions and macro-static methods.
Compiler errors related to metadata.