{@a overview}
-## 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 the _Angular compiler_.
+the components and templates must be converted to executable JavaScript by an _Angular compiler_.
-
+Angular offers two ways to compile your application:
- Watch compiler author Tobias Bosch explain the Angular Compiler at AngularConnect 2016.
+1. **_Just-in-Time_ (JIT)**, which compiles your app in the browser at runtime
+1. **_Ahead-of-Time_ (AOT)**, which compiles your app at build time.
-
+JIT compilation is the default when you run the _build-only_ or the _build-and-serve-locally_ CLI commands:
-You can compile the app in the browser, at runtime, as the application loads, using the **_just-in-time_ (JIT) compiler**.
-This is the standard development approach shown throughout the documentation.
-It's great but it has shortcomings.
+
+ ng build
+ ng serve
+
-JIT compilation incurs a runtime performance penalty.
-Views take longer to render because of the in-browser compilation step.
-The application is bigger because it includes the Angular compiler
-and a lot of library code that the application won't actually need.
-Bigger apps take longer to transmit and are slower to load.
+{@a compile}
-Compilation can uncover many component-template binding errors.
-JIT compilation discovers them at runtime, which is late in the process.
+For AOT compilation, append the `--aot` flags to the _build-only_ or the _build-and-serve-locally_ CLI commands:
-The **_ahead-of-time_ (AOT) compiler** can catch template errors early and improve performance
-by compiling at build time.
+
+ ng build --aot
+ ng serve --aot
+
-{@a aot-jit}
+
-## _Ahead-of-time_ (AOT) vs _just-in-time_ (JIT)
+The `--prod` meta-flag compiles with AOT by default.
-There is actually only one Angular compiler. The difference between AOT and JIT is a matter of timing and tooling.
-With AOT, the compiler runs once at build time using one set of libraries;
-with JIT it runs every time for every user at runtime using a different set of libraries.
+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}
-## Why do AOT compilation?
+## Why compile with AOT?
*Faster rendering*
@@ -60,7 +66,6 @@ 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.
-
*Detect template errors earlier*
The AOT compiler detects and reports template binding errors during the build step
@@ -72,517 +77,896 @@ AOT compiles HTML templates and components into JavaScript files long before the
With no templates to read and no risky client-side HTML or JavaScript evaluation,
there are fewer opportunities for injection attacks.
-{@a compile}
+## Angular Metadata and AOT
-## Compile with AOT
+The Angular **AOT compiler** extracts and interprets **metadata** about the parts of the application that Angular is supposed to manage.
-Preparing for offline compilation takes a few simple steps.
-Take the Setup as a starting point.
-A few minor changes to the lone `app.component` lead to these two class and HTML files:
+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.
-Install a few new npm dependencies with the following command:
+In the following example, the `@Component()` metadata object and the class constructor tell Angular how to create and display an instance of `TypicalComponent`.
-
- npm install @angular/compiler-cli @angular/platform-server --save
-
+```typescript
+@Component({
+ selector: 'app-typical',
+ template: '
A typical component for {{data.name}}
'
+)}
+export class TypicalComponent {
+ @Input() data: TypicalData;
+ constructor(private someService: SomeService) { ... }
+}
+```
-You will run the `ngc` compiler provided in the `@angular/compiler-cli` npm package
-instead of the TypeScript compiler (`tsc`).
+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.
-`ngc` is a drop-in replacement for `tsc` and is configured much the same way.
+## Metadata restrictions
-`ngc` requires its own `tsconfig.json` with AOT-oriented settings.
-Copy the original `src/tsconfig.json` to a file called `tsconfig-aot.json` on the project root,
-then modify it as follows.
+You write metadata in a _subset_ of TypeScript that must conform to the following general constraints:
-
-
+1. Limit [expression syntax](#expression-syntax) to the supported subset of JavaScript.
+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 `compilerOptions` section is unchanged except for one property.
-**Set the `module` to `es2015`**.
-This is important as explained later in the [Tree Shaking](guide/aot-compiler#tree-shaking) section.
+The next sections elaborate on these points.
-What's really new is the `ngc` section at the bottom called `angularCompilerOptions`.
-Its `genDir` property tells the compiler
-to store the compiled output files in a new `aot` folder.
+## How AOT works
-The `"skipMetadataEmit" : true` property prevents the compiler from generating metadata files with the compiled application.
-Metadata files are not necessary when targeting TypeScript files, so there is no reason to include them.
+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.
-***Component-relative template URLS***
+## Phase 1: analysis
-The AOT compiler requires that `@Component` URLS for external templates and CSS files be _component-relative_.
-That means that the value of `@Component.templateUrl` is a URL value _relative_ to the component class file.
-For example, an `'app.component.html'` URL means that the template file is a sibling of its companion `app.component.ts` file.
+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.
-While JIT app URLs are more flexible, stick with _component-relative_ URLs for compatibility with AOT compilation.
+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.
-***Compiling the application***
+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).
-Initiate AOT compilation from the command line using the previously installed `ngc` compiler by executing:
+
-
- node_modules/.bin/ngc -p tsconfig-aot.json
-
+Angular's [schema.ts](https://github.com/angular/angular/blob/master/packages/tsc-wrapped/src/schema.ts)
+describes the JSON format as a collection of TypeScript interfaces.
+
+
+
+{@a expression-syntax}
+### Expression syntax
+
+The _collector_ only understands a subset of JavaScript.
+Define metadata objects with the following limited syntax:
+
+Syntax | Example
+-----------------------------------|-----------------------------------
+Literal object | `{cherry: true, apple: true, mincemeat: false}`
+Literal array | `['cherries', 'flour', 'sugar']`
+Spread in literal array | `['apples', 'flour', ...the_rest]`
+Calls | `bake(ingredients)`
+New | `new Oven()`
+Property access | `pie.slice`
+Array index | `ingredients[0]`
+Identifier reference | `Component`
+A template string | `pie is ${multiplier} times better than cake`
+Literal string | `'pi'`
+Literal number | `3.14153265`
+Literal boolean | `true`
+Literal null | `null`
+Supported prefix operator | `!cake`
+Supported Binary operator | `a + b`
+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.
- Windows users should surround the `ngc` command in double quotes:
-
- "node_modules/.bin/ngc" -p tsconfig-aot.json
-
+ 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
+ }
+ ```
-`ngc` expects the `-p` switch to point to a `tsconfig.json` file or a folder containing a `tsconfig.json` file.
+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.
-After `ngc` completes, look for a collection of _NgFactory_ files in the `aot` folder.
-The `aot` folder is the directory specified as `genDir` in `tsconfig-aot.json`.
+
-These factory files are essential to the compiled application.
-Each component factory creates an instance of the component at runtime by combining the original class file
-and a JavaScript representation of the component's template.
-Note that the original component class is still referenced internally by the generated factory.
+{@a function-expression}
+{@a arrow-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.
- The curious can open `aot/app.component.ngfactory.ts` to see the original Angular template syntax
- compiled to TypeScript, its intermediate form.
+Consider the following component decorator:
- JIT compilation generates these same _NgFactories_ in memory where they are largely invisible.
- AOT compilation reveals them as separate, physical files.
+```ts
+@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_.
- Do not edit the _NgFactories_! Re-compilation replaces these files and all edits will be lost.
+You can fix the error by converting to this:
-
+```ts
+export function serverFactory() {
+ return new Server();
+}
-{@a bootstrap}
+@Component({
+ ...
+ providers: [{provide: server, useFactory: serverFactory}]
+})
+```
-## Bootstrap
+Beginning in version 5, the compiler automatically performs this rewritting while emitting the `.js` file.
-The AOT approach changes application bootstrapping.
+### Limited function calls
-Instead of bootstrapping `AppModule`, you bootstrap the application with the generated module factory, `AppModuleNgFactory`.
+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.
-Make a copy of `main.ts` and name it `main-jit.ts`.
-This is the JIT version; set it aside as you may need it [later](guide/aot-compiler#run-jit "Running with JIT").
+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).
-Open `main.ts` and convert it to AOT compilation.
-Switch from the `platformBrowserDynamic.bootstrap` used in JIT compilation to
-`platformBrowser().bootstrapModuleFactory` and pass in the AOT-generated `AppModuleNgFactory`.
-Here is AOT bootstrap in `main.ts` next to the original JIT version:
+### 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.
-Be sure to [recompile](guide/aot-compiler#compile) with `ngc`!
+For example, the _collector_ can evaluate the expression `1 + 2 + 3 + 4` and replace it with the result, `10`.
-{@a tree-shaking}
+This process is called _folding_. An expression that can be reduced in this manner is _foldable_.
-## Tree shaking
+{@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.
-AOT compilation sets the stage for further optimization through a process called _tree shaking_.
-A tree shaker walks the dependency graph, top to bottom, and _shakes out_ unused code like
-dead leaves in a tree.
+Consider the following component definition:
-Tree shaking can greatly reduce the downloaded size of the application
-by removing unused portions of both source and library code.
-In fact, most of the reduction in small apps comes from removing unreferenced Angular features.
+```ts
+const template = '
{{hero.name}}
';
-For example, this demo application doesn't use anything from the `@angular/forms` library.
-There is no reason to download forms-related Angular code and tree shaking ensures that you don't.
+@Component({
+ selector: 'app-hero',
+ template: template
+})
+export class HeroComponent {
+ @Input() hero: Hero;
+}
+```
-Tree shaking and AOT compilation are separate steps.
-Tree shaking can only target JavaScript code.
-AOT compilation converts more of the application to JavaScript,
-which in turn makes more of the application "tree shakable".
+The compiler could not refer to the `template` constant because it isn't exported.
-{@a rollup}
+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:
-### Rollup
+```TypeScript
+@Component({
+ selector: 'app-hero',
+ template: '
{{hero.name}}
'
+})
+export class HeroComponent {
+ @Input() hero: Hero;
+}
+```
-This cookbook illustrates a tree shaking utility called _Rollup_.
+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`.
-Rollup statically analyzes the application by following the trail of `import` and `export` statements.
-It produces a final code _bundle_ that excludes code that is exported, but never imported.
+You can take this example a step further by including the `template` constant in another expression:
-Rollup can only tree shake `ES2015` modules which have `import` and `export` statements.
+```TypeScript
+const template = '
'
+})
+export class HeroComponent {
+ @Input() hero: Hero;
+}
+```
- Recall that `tsconfig-aot.json` is configured to produce `ES2015` modules.
- It's not important that the code itself be written with `ES2015` syntax such as `class` and `const`.
- What matters is that the code uses ES `import` and `export` statements rather than `require` statements.
+The _collector_ reduces this expression to its equivalent _folded_ string:
-
+`'
{{hero.name}}
{{hero.title}}
'`.
-In the terminal window, install the Rollup dependencies with this command:
+#### Foldable syntax
-
- npm install rollup rollup-plugin-node-resolve rollup-plugin-commonjs rollup-plugin-uglify --save-dev
-
+The following table describes which expressions the _collector_ can and cannot fold:
-Next, create a configuration file (`rollup-config.js`)
-in the project root directory to tell Rollup how to process the application.
-The cookbook configuration file looks like this.
+Syntax | Foldable
+-----------------------------------|-----------------------------------
+Literal object | yes
+Literal array | yes
+Spread in literal array | no
+Calls | no
+New | no
+Property access | yes, if target is foldable
+Array index | yes, if target and index are foldable
+Identifier reference | yes, if it is a reference to a local
+A template with no substitutions | yes
+A template with substitutions | yes, if the substitutions are foldable
+Literal string | yes
+Literal number | yes
+Literal boolean | yes
+Literal null | yes
+Supported prefix operator | yes, if operand is foldable
+Supported binary operator | yes, if both left and right are foldable
+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.
-This config file tells Rollup that the app entry point is `src/app/main.js` .
-The `dest` attribute tells Rollup to create a bundle called `build.js` in the `dist` folder.
-It overrides the default `onwarn` method in order to skip annoying messages about the AOT compiler's use of the `this` keyword.
-The next section covers the plugins in more depth.
+## Phase 2: code generation
-{@a rollup-plugins}
+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.
-### Rollup Plugins
+It's the compiler's job to interpret the `.metadata.json` in the code generation phase.
-Optional plugins filter and transform the Rollup inputs and output.
+The compiler understands all syntax forms that the _collector_ supports, but it may reject _syntactically_ correct metadata if the _semantics_ violate compiler rules.
-*RxJS*
+The compiler can only reference _exported symbols_.
-Rollup expects application source code to use `ES2015` modules.
-Not all external dependencies are published as `ES2015` modules.
-In fact, most are not. Many of them are published as _CommonJS_ modules.
+Decorated component class members must be public. You cannot make an `@Input()` property private or internal.
-The _RxJs_ Observable library is an essential Angular dependency published as an ES5 JavaScript _CommonJS_ module.
+Data bound properties must also be public.
-Luckily, there is a Rollup plugin that modifies _RxJs_
-to use the ES `import` and `export` statements that Rollup requires.
-Rollup then preserves the parts of `RxJS` referenced by the application
-in the final bundle. Using it is straigthforward. Add the following to
-the `plugins` array in `rollup-config.js`:
+```TypeScript
+// BAD CODE - title is private
+@Component({
+ selector: 'app-root',
+ template: '
{{title}}
'
+})
+export class AppComponent {
+ private title = 'My App'; // Bad
+}
+```
-
-
+{@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.
-*Minification*
-Rollup tree shaking reduces code size considerably. Minification makes it smaller still.
-This cookbook relies on the _uglify_ Rollup plugin to minify and mangle the code.
-Add the following to the `plugins` array:
+### New instances
-
-
+The compiler only allows metadata that create instances of the class `InjectionToken` from `@angular/core`.
-
+### Annotations/Decorators
- In a production setting, you would also enable gzip on the web server to compress
- the code into an even smaller package going over the wire.
+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`
-{@a run-rollup}
-### Run Rollup
+### Macro-functions and macro-static methods
-Execute the Rollup process with this command:
+The compiler also supports _macros_ in the form of functions or static
+methods that return an expression.
-
- node_modules/.bin/rollup -c rollup-config.js
-
+For example, consider the following function:
-
+```TypeScript
+export function wrapInArray(value: T): T[] {
+ return [value];
+}
+```
- Windows users should surround the `rollup` command in double quotes:
-
- "node_modules/.bin/rollup" -c rollup-config.js
-
+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.
-
+You might use `wrapInArray()` like this:
-{@a load}
+```TypeScript
+@NgModule({
+ declarations: wrapInArray(TypicalComponent)
+})
+export class TypicalModule {}
+```
-## Load the bundle
+The compiler treats this usage as if you had written:
-Loading the generated application bundle does not require a module loader like SystemJS.
-Remove the scripts that concern SystemJS.
-Instead, load the bundle file using a single `