The Angular **AOT compiler** turns your TypeScript source code into runnable JavaScript.
As part of that process, the compiler extracts and interprets **metadata** about the parts of the application that Angular is supposed to manage.
You write metadata in a _subset_ of TypeScript. This guide explains why a subset is necessary, describes the subset constraints, and what happens when you step outside of those constraints.
## Angular metadata
Angular metadata tells Angular how to construct instances of your application classes and interact with them at runtime.
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`.
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.
## Compile ahead-of-time (AOT)
You should use AOT to compile an application that must launch quickly.
The browser downloads a smaller set of safely-compiled, application module(s) and libraries that it can parse quickly and run almost immediately.
The AOT compiler produces a number of files, including the application JavaScript that ultimately runs in the browser. It then statically analyzes your source code and interprets the Angular metadata without actually running the application.
To compile the app, run the `ngc` stand-alone tool as part of your build process.
2. Only reference exported symbols after [code folding](#folding).
3. Only call [functions supported](#supported-functions) by the compiler.
4. Decorated and data-bound class members must be public.
The next sections elaborate on these points.
## How AOT works
It helps to think of the AOT compiler as having two phases: a code analysis phase in which it simply records a representation of the source; and a code generation phase in which the compiler's `StaticReflector` handles the interpretation as well as places restrictions on what it interprets.
## 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)](https://en.wikipedia.org/wiki/Abstract_syntax_tree).
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.
<divclass="l-sub-section">
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.
</div>
{@a function-expression}
{@a arror-functions}
### No arrow functions
The AOT compiler does not support [function expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)
and [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), also called _lambda_ functions.
Consider the following component decorator:
```ts
@Component({
...
providers: [{provide: server, useFactory: () => new Server()}]
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](#supported-functions).
The _collector_ may be able to evaluate an expression during collection and record the result in the `.metadata.json` instead of the original expression.
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:
Conditional operator | yes, if condition is foldable
Parentheses | yes, if the expression is foldable
If an expression is not foldable, the collector writes it to `.metadata.json` as an [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree) for the compiler to resolve.
The _collector_ makes no attempt to understand the metadata that it collects and outputs to `.metadata.json`. It represents the metadata as best it can and records errors when it detects a metadata syntax violation.
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.
Most importantly, the compiler only generates code to create instances of certain classes, support certain decorators, and call certain functions from the following lists.
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.
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`](api/router/RouterModule) exports two macro static methods, `forRoot` and `forChild`, to help declare root and child routes.
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.
Without rewriting, this would be invalid because lambdas are not supported and `TypicalServer` is not exported.
To allow this, the compiler automatically rewrites this to something like:
```ts
class TypicalServer {
}
export const ɵ0 = () => new 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.
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](#expression-syntax)
when writing Angular metadata
and be wary of new or unusual TypeScript features.
<hr>
{@a reference-to-a-local-symbol}
<h3class="no-toc">Reference to a local (non-exported) symbol</h3>
<divclass="alert is-helpful">
_Reference to a local (non-exported) symbol 'symbol name'. Consider exporting the symbol._
</div>
The compiler encountered a referenced to a locally defined symbol that either wasn't exported or wasn't initialized.
Here's a `provider` example of the problem.
```
// 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](#folding) 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.
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`](#only-initialized-variables)".
<hr>
{@a only-initialized-variables}
<h3class="no-toc">Only initialized variables and constants</h3>
<divclass="alert is-helpful">
_Only initialized variables and constants can be referenced because the value of this variable is needed by the template compiler._
</div>
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.
```
// ERROR - not initialized there either
import { someTemplate } from './config';
@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 {}
```
<hr>
<h3class="no-toc">Reference to a non-exported class</h3>
<divclass="alert is-helpful">
_Reference to a non-exported class <classname>. Consider exporting the class._
</div>
Metadata referenced a class that wasn't exported.
For example, you may have defined a class and used it as an injection token in a providers array
<h3class="no-toc">Destructured variable or constant not supported</h3>
<divclass="alert is-helpful">
_Referencing an exported destructured variable or constant is not supported by the template compiler. Consider simplifying this to avoid destructuring._
</div>
The compiler does not support references to variables assigned by [destructuring](https://www.typescriptlang.org/docs/handbook/variable-declarations.html#destructuring).
For example, you cannot write something like this:
<code-examplelinenums="false">
// ERROR
import { configuration } from './configuration';
// destructured assignment to foo and bar
const {foo, bar} = configuration;
...
providers: [
{provide: Foo, useValue: foo},
{provide: Bar, useValue: bar},
]
...
</code-example>
To correct this error, refer to non-destructured values.
<code-examplelinenums="false">
// CORRECTED
import { configuration } from './configuration';
...
providers: [
{provide: Foo, useValue: configuration.foo},
{provide: Bar, useValue: configuration.bar},
]
...
</code-example>
<hr>
<h3class="no-toc">Could not resolve type</h3>
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,
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).
<code-examplelinenums="false">
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
The compiler can understand simple enum values but not complex values such as those derived from computed properties.
<code-examplelinenums="false">
// ERROR
enum Colors {
Red = 1,
White,
Blue = "Blue".length // computed
}
...
providers: [
{ provide: BaseColor, useValue: Colors.White } // ok
{ provide: DangerColor, useValue: Colors.Red } // ok
{ provide: StrongColor, useValue: Colors.Blue } // bad
]
...
</code-example>
Avoid referring to enums with complicated initializers or computed properties.
<hr>
{@a tagged-template-expressions-not-supported}
<h3class="no-toc">Tagged template expressions are not supported</h3>
<divclass="alert is-helpful">
_Tagged template expressions are not supported in metadata._
</div>
The compiler encountered a JavaScript ES2015 [tagged template expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals) such as,
```
// ERROR
const expression = 'funky';
const raw = String.raw`A tagged template ${expression} string`;