From 7186c9c83962e2346943562419082b8a4135a7e0 Mon Sep 17 00:00:00 2001 From: Ward Bell Date: Thu, 2 Nov 2017 14:34:21 -0700 Subject: [PATCH] docs: AOT guide for CLI #19510 (#19818) --- aio/content/examples/aot-compiler/e2e-spec.ts | 27 - .../examples/aot-compiler/example-config.json | 4 - .../examples/aot-compiler/rollup-config.js | 33 - .../aot-compiler/src/app/app.component.html | 7 - .../aot-compiler/src/app/app.component.ts | 15 - .../aot-compiler/src/app/app.module.ts | 12 - .../examples/aot-compiler/src/index-jit.html | 24 - .../examples/aot-compiler/src/index.html | 20 - .../examples/aot-compiler/src/main-jit.ts | 6 - aio/content/examples/aot-compiler/src/main.ts | 6 - .../examples/aot-compiler/tsconfig-aot.json | 27 - aio/content/guide/aot-compiler.md | 1240 +++++++++++------ aio/content/guide/docs-style-guide.md | 4 +- aio/content/guide/metadata.md | 913 ------------ aio/content/guide/quickstart.md | 18 +- .../aot-compiler/toh-pt6-bundle-200w.png | Bin 18909 -> 0 bytes .../aot-compiler/toh-pt6-bundle-400w.png | Bin 61812 -> 0 bytes .../aot-compiler/toh-pt6-bundle-560w.png | Bin 103650 -> 0 bytes .../toh-pt6-bundle-700w.png | Bin .../toh-pt6-bundle.png | Bin aio/content/navigation.json | 5 - aio/firebase.json | 5 +- 22 files changed, 820 insertions(+), 1546 deletions(-) delete mode 100644 aio/content/examples/aot-compiler/e2e-spec.ts delete mode 100644 aio/content/examples/aot-compiler/example-config.json delete mode 100644 aio/content/examples/aot-compiler/rollup-config.js delete mode 100644 aio/content/examples/aot-compiler/src/app/app.component.html delete mode 100644 aio/content/examples/aot-compiler/src/app/app.component.ts delete mode 100644 aio/content/examples/aot-compiler/src/app/app.module.ts delete mode 100644 aio/content/examples/aot-compiler/src/index-jit.html delete mode 100644 aio/content/examples/aot-compiler/src/index.html delete mode 100644 aio/content/examples/aot-compiler/src/main-jit.ts delete mode 100644 aio/content/examples/aot-compiler/src/main.ts delete mode 100644 aio/content/examples/aot-compiler/tsconfig-aot.json delete mode 100644 aio/content/guide/metadata.md delete mode 100644 aio/content/images/guide/aot-compiler/toh-pt6-bundle-200w.png delete mode 100644 aio/content/images/guide/aot-compiler/toh-pt6-bundle-400w.png delete mode 100644 aio/content/images/guide/aot-compiler/toh-pt6-bundle-560w.png rename aio/content/images/guide/{aot-compiler => docs-style-guide}/toh-pt6-bundle-700w.png (100%) rename aio/content/images/guide/{aot-compiler => docs-style-guide}/toh-pt6-bundle.png (100%) diff --git a/aio/content/examples/aot-compiler/e2e-spec.ts b/aio/content/examples/aot-compiler/e2e-spec.ts deleted file mode 100644 index 4744f06e50..0000000000 --- a/aio/content/examples/aot-compiler/e2e-spec.ts +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; // necessary for es6 output in node - -import { browser, element, by } from 'protractor'; - -/* tslint:disable:quotemark */ -describe('AOT Compilation', function () { - - beforeAll(function () { - browser.get(''); - }); - - it('should load page and click button', function (done: any) { - let headingSelector = element.all(by.css('h1')).get(0); - expect(headingSelector.getText()).toEqual('Hello Angular'); - - expect(element.all(by.xpath('//div[text()="Magneta"]')).get(0).isPresent()).toBe(true); - expect(element.all(by.xpath('//div[text()="Bombasto"]')).get(0).isPresent()).toBe(true); - expect(element.all(by.xpath('//div[text()="Magma"]')).get(0).isPresent()).toBe(true); - expect(element.all(by.xpath('//div[text()="Tornado"]')).get(0).isPresent()).toBe(true); - - let toggleButton = element.all(by.css('button')).get(0); - toggleButton.click().then(function() { - expect(headingSelector.isPresent()).toBe(false); - done(); - }); - }); -}); diff --git a/aio/content/examples/aot-compiler/example-config.json b/aio/content/examples/aot-compiler/example-config.json deleted file mode 100644 index 1bbaaad530..0000000000 --- a/aio/content/examples/aot-compiler/example-config.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "build": "build:aot", - "projectType": "systemjs" -} diff --git a/aio/content/examples/aot-compiler/rollup-config.js b/aio/content/examples/aot-compiler/rollup-config.js deleted file mode 100644 index 135e516f0b..0000000000 --- a/aio/content/examples/aot-compiler/rollup-config.js +++ /dev/null @@ -1,33 +0,0 @@ -// #docregion -import nodeResolve from 'rollup-plugin-node-resolve'; -import commonjs from 'rollup-plugin-commonjs'; -import uglify from 'rollup-plugin-uglify'; - -// #docregion config -export default { - entry: 'src/main.js', - dest: 'src/build.js', // output a single application bundle - sourceMap: true, - format: 'iife', - onwarn: function(warning) { - // Skip certain warnings - - // should intercept ... but doesn't in some rollup versions - if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; } - - // console.warn everything else - console.warn( warning.message ); - }, - plugins: [ - nodeResolve({jsnext: true, module: true}), - // #docregion commonjs - commonjs({ - include: 'node_modules/rxjs/**', - }), - // #enddocregion commonjs - // #docregion uglify - uglify() - // #enddocregion uglify - ] -}; -// #enddocregion config diff --git a/aio/content/examples/aot-compiler/src/app/app.component.html b/aio/content/examples/aot-compiler/src/app/app.component.html deleted file mode 100644 index 1d3a8de932..0000000000 --- a/aio/content/examples/aot-compiler/src/app/app.component.html +++ /dev/null @@ -1,7 +0,0 @@ - - -

Hello Angular

- -

List of Heroes

-
{{hero}}
- diff --git a/aio/content/examples/aot-compiler/src/app/app.component.ts b/aio/content/examples/aot-compiler/src/app/app.component.ts deleted file mode 100644 index 879f7f663c..0000000000 --- a/aio/content/examples/aot-compiler/src/app/app.component.ts +++ /dev/null @@ -1,15 +0,0 @@ -// #docregion -import { Component } from '@angular/core'; - -@Component({ - selector: 'my-app', - templateUrl: './app.component.html' -}) -export class AppComponent { - showHeading = true; - heroes = ['Magneta', 'Bombasto', 'Magma', 'Tornado']; - - toggleHeading() { - this.showHeading = !this.showHeading; - } -} diff --git a/aio/content/examples/aot-compiler/src/app/app.module.ts b/aio/content/examples/aot-compiler/src/app/app.module.ts deleted file mode 100644 index b4fc185c24..0000000000 --- a/aio/content/examples/aot-compiler/src/app/app.module.ts +++ /dev/null @@ -1,12 +0,0 @@ -// #docregion -import { NgModule } from '@angular/core'; -import { BrowserModule } from '@angular/platform-browser'; - -import { AppComponent } from './app.component'; - -@NgModule({ - imports: [ BrowserModule ], - declarations: [ AppComponent ], - bootstrap: [ AppComponent ] -}) -export class AppModule { } diff --git a/aio/content/examples/aot-compiler/src/index-jit.html b/aio/content/examples/aot-compiler/src/index-jit.html deleted file mode 100644 index db41485320..0000000000 --- a/aio/content/examples/aot-compiler/src/index-jit.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - Ahead of time compilation (JIT) - - - - - - - - - - - - - - - Loading... - - diff --git a/aio/content/examples/aot-compiler/src/index.html b/aio/content/examples/aot-compiler/src/index.html deleted file mode 100644 index c79a60dd1b..0000000000 --- a/aio/content/examples/aot-compiler/src/index.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - Ahead of time compilation - - - - - - - - - - Loading... - - - - - diff --git a/aio/content/examples/aot-compiler/src/main-jit.ts b/aio/content/examples/aot-compiler/src/main-jit.ts deleted file mode 100644 index 88e2c16ed5..0000000000 --- a/aio/content/examples/aot-compiler/src/main-jit.ts +++ /dev/null @@ -1,6 +0,0 @@ -// #docregion -import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; -import { AppModule } from './app/app.module'; - -console.log('Running JIT compiled'); -platformBrowserDynamic().bootstrapModule(AppModule); diff --git a/aio/content/examples/aot-compiler/src/main.ts b/aio/content/examples/aot-compiler/src/main.ts deleted file mode 100644 index 22298fab9c..0000000000 --- a/aio/content/examples/aot-compiler/src/main.ts +++ /dev/null @@ -1,6 +0,0 @@ -// #docregion -import { platformBrowser } from '@angular/platform-browser'; -import { AppModuleNgFactory } from './app/app.module.ngfactory'; - -console.log('Running AOT compiled'); -platformBrowser().bootstrapModuleFactory(AppModuleNgFactory); diff --git a/aio/content/examples/aot-compiler/tsconfig-aot.json b/aio/content/examples/aot-compiler/tsconfig-aot.json deleted file mode 100644 index 718373821c..0000000000 --- a/aio/content/examples/aot-compiler/tsconfig-aot.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "compilerOptions": { - "target": "es5", - "module": "es2015", - "moduleResolution": "node", - "sourceMap": true, - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "lib": ["es2015", "dom"], - "noImplicitAny": true, - "suppressImplicitAnyIndexErrors": true, - "typeRoots": [ - "./node_modules/@types/" - ] - }, - - "files": [ - "src/app/app.module.ts", - "src/main.ts" - ], - - "angularCompilerOptions": { - "annotationsAs": "decorators", - "genDir": ".", - "skipMetadataEmit" : true - } -} diff --git a/aio/content/guide/aot-compiler.md b/aio/content/guide/aot-compiler.md index 9a3205e777..9c32535893 100644 --- a/aio/content/guide/aot-compiler.md +++ b/aio/content/guide/aot-compiler.md @@ -1,15 +1,8 @@ -# Ahead-of-Time Compilation +# The Ahead-of-Time (AOT) Compiler -This cookbook describes how to radically improve performance by compiling _ahead-of-time_ (AOT) -during a build process. +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. -{@a overview} - -## Overview - -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_. +This guide explains how to to build with the AOT compiler and how to write Angular metadata that AOT can compile.
@@ -17,33 +10,46 @@ the components and templates must be converted to executable JavaScript by the _
-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. +{@a overview} -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. +## Angular compilation -Compilation can uncover many component-template binding errors. -JIT compilation discovers them at runtime, which is late in the process. +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_. -The **_ahead-of-time_ (AOT) compiler** can catch template errors early and improve performance -by compiling at build time. +Angular offers two ways to compile your application: -{@a aot-jit} +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. -## _Ahead-of-time_ (AOT) vs _just-in-time_ (JIT) +JIT compilation is the default when you run the _build-only_ or the _build-and-serve-locally_ CLI commands: -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. + + 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: + + + ng build --aot + ng serve --aot + + +
+ +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} -## 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*** - -Initiate AOT compilation from the command line using the previously installed `ngc` compiler by executing: - - - node_modules/.bin/ngc -p tsconfig-aot.json - +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).
- Windows users should surround the `ngc` command in double quotes: - - "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.
-`ngc` expects the `-p` switch to point to a `tsconfig.json` file or a folder containing a `tsconfig.json` file. +{@a expression-syntax} +### Expression syntax -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`. +The _collector_ only understands a subset of JavaScript. +Define metadata objects with the following limited syntax: -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. +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.
- The curious can open `aot/app.component.ngfactory.ts` to see the original Angular template syntax - compiled to TypeScript, its intermediate form. + If you want `ngc` to report syntax errors immediately rather than produce a `.metadata.json` file with errors, set the `strictMetadataEmit` option in `tsconfig`. - JIT compilation generates these same _NgFactories_ in memory where they are largely invisible. - AOT compilation reveals them as separate, physical files. +``` + "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.
-
+{@a function-expression} +{@a arrow-functions} +### No arrow functions - Do not edit the _NgFactories_! Re-compilation replaces these files and all edits will be lost. +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 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_. + +You can fix the error by converting to this: + +```ts +export function serverFactory() { + return new Server(); +} + +@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](#supported-functions). + + +### 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. + +Consider the following component definition: + +```ts +const template = '
{{hero.name}}
'; + +@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: + +```TypeScript +@Component({ + selector: 'app-hero', + template: '
{{hero.name}}
' +}) +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: + +```TypeScript +const template = '
{{hero.name}}
'; + +@Component({ + selector: 'app-hero', + template: template + '
{{hero.title}}
' +}) +export class HeroComponent { + @Input() hero: Hero; +} +``` + +The _collector_ reduces this expression to its equivalent _folded_ string: + +`'
{{hero.name}}
{{hero.title}}
'`. + +#### Foldable syntax + +The following table describes which expressions the _collector_ can and cannot fold: + +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. + + +## Phase 2: code generation + +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. + +The compiler can only reference _exported symbols_. + +Decorated component class members must be public. You cannot make an `@Input()` property private or internal. + +Data bound properties must also be public. + +```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. + + +### 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` + + +### Macro-functions and macro-static methods + +The compiler also supports _macros_ in the form of functions or static +methods that return an expression. + +For example, consider the following function: + +```TypeScript +export function wrapInArray(value: T): T[] { + return [value]; +} +``` + +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: + +```TypeScript +@NgModule({ + declarations: wrapInArray(TypicalComponent) +}) +export class TypicalModule {} +``` + +The compiler treats this usage as if you had written: + +```TypeScript +@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`](api/router/RouterModule) exports two macro static methods, `forRoot` and `forChild`, to help declare root and child routes. +Review the [source code](https://github.com/angular/angular/blob/master/packages/router/src/router_module.ts#L139 "RouterModule.forRoot source code") +for these methods to see how macros can simplify configuration of complex Angular modules. + +### 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. + + + +You might write something like: + +```ts +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. + +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. + + +## Metadata Errors + +The following are metadata errors you may encounter, with explanations and suggested corrections. + +[Expression form not supported](#expression-form-not-supported)
+[Reference to a local (non-exported) symbol](#reference-to-a-local-symbol)
+[Only initialized variables and constants](#only-initialized-variables)
+[Reference to a non-exported class](#reference-to-a-non-exported-class)
+[Reference to a non-exported function](#reference-to-a-non-exported-function)
+[Function calls are not supported](#function-calls-not-supported)
+[Destructured variable or constant not supported](#destructured-variable-not-supported)
+[Could not resolve type](#could-not-resolve-type)
+[Name expected](#name-expected)
+[Unsupported enum member name](#unsupported-enum-member-name)
+[Tagged template expressions are not supported](#tagged-template-expressions-not-supported)
+[Symbol reference expected](#symbol-reference-expected)
+ +
+ +

Expression form not supported

+ +The compiler encountered an expression it didn't understand while evalutating Angular metadata. + +Language features outside of the compiler's [restricted expression syntax](#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](#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

+ +
+ +_Reference to a local (non-exported) symbol 'symbol name'. Consider exporting the symbol._
-{@a bootstrap} +The compiler encountered a referenced to a locally defined symbol that either wasn't exported or wasn't initialized. -## Bootstrap +Here's a `provider` example of the problem. -The AOT approach changes application bootstrapping. +``` +// ERROR +let foo: number; // neither exported nor initialized -Instead of bootstrapping `AppModule`, you bootstrap the application with the generated module factory, `AppModuleNgFactory`. +@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. -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"). +You could fix the problem by initializing `foo`. -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`. +``` +let foo = 42; // initialized +``` -Here is AOT bootstrap in `main.ts` next to the original JIT version: +The compiler will [fold](#folding) the expression into the provider as if you had written this. - - - - - - +``` + providers: [ + { provide: Foo, useValue: 42 } + ] +``` -Be sure to [recompile](guide/aot-compiler#compile) with `ngc`! +Alternatively, you can fix it by exporting `foo` with the expectation that `foo` will be assigned at runtime when you actually know its value. -{@a tree-shaking} +``` +// CORRECTED +export let foo: number; // exported -## Tree shaking +@Component({ + selector: 'my-component', + template: ... , + providers: [ + { provide: Foo, useValue: foo } + ] +}) +export class MyComponent {} +``` -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. +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. -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. +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. -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. +``` +// ERROR +export let someTemplate: string; // exported but not initialized -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". +@Component({ + selector: 'my-component', + template: someTemplate +}) +export class MyComponent {} +``` -{@a rollup} +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)". -### Rollup +
-This cookbook illustrates a tree shaking utility called _Rollup_. +{@a only-initialized-variables} +

Only initialized variables and constants

-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. +
-Rollup can only tree shake `ES2015` modules which have `import` and `export` statements. - -
- - 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. +_Only initialized variables and constants can be referenced because the value of this variable is needed by the template compiler._
-In the terminal window, install the Rollup dependencies with this command: +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. - - npm install rollup rollup-plugin-node-resolve rollup-plugin-commonjs rollup-plugin-uglify --save-dev - +The following example tries to set the component's `template` property to the value of +the exported `someTemplate` variable which is declared but _unassigned_. -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. +``` +// ERROR +export let someTemplate: string; - - +@Component({ + selector: 'my-component', + template: someTemplate +}) +export class MyComponent {} +``` -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. +You'd also get this error if you imported `someTemplate` from some other module and neglected to initialize it there. -The next section covers the plugins in more depth. +``` +// ERROR - not initialized there either +import { someTemplate } from './config'; -{@a rollup-plugins} +@Component({ + selector: 'my-component', + template: someTemplate +}) +export class MyComponent {} +``` -### Rollup Plugins +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. -Optional plugins filter and transform the Rollup inputs and output. +To correct this error, provide the initial value of the variable in an initializer clause _on the same line_. -*RxJS* +``` +// CORRECTED +export let someTemplate = '

Greetings from Angular

'; -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. +@Component({ + selector: 'my-component', + template: someTemplate +}) +export class MyComponent {} +``` -The _RxJs_ Observable library is an essential Angular dependency published as an ES5 JavaScript _CommonJS_ module. +
-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`: +

Reference to a non-exported class

- - +
-*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: - - - - -
- - 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. +_Reference to a non-exported class . Consider exporting the class._
-{@a run-rollup} +Metadata referenced a class that wasn't exported. -### Run Rollup +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. -Execute the Rollup process with this command: +``` +// ERROR +abstract class MyStrategy { } - - node_modules/.bin/rollup -c rollup-config.js - + ... + providers: [ + { provide: MyStrategy, useValue: ... } + ] + ... +``` -
+Angular generates a class factory in a separate module and that +factory [can only access exported classes](#exported-symbols). +To correct this error, export the referenced class. - Windows users should surround the `rollup` command in double quotes: - - "node_modules/.bin/rollup" -c rollup-config.js - +``` +// CORRECTED +export abstract class MyStrategy { } + + ... + providers: [ + { provide: MyStrategy, useValue: ... } + ] + ... +``` +
+ +

Reference to a non-exported function

+ +Metadata referenced a function that wasn't exported. + +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](#exported-symbols). +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

+ +
+ +_Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function._
-{@a load} +The compiler does not currently support [function expressions or lambda functions](#function-expression). +For example, you cannot set a provider's `useFactory` to an anonymous function or arrow function like this. -## Load the bundle +``` +// 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'; -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 `