# The Ahead-of-Time (AOT) Compiler 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. Angular 的“预先(AOT)编译器”会在构建期间把 Angular 应用的 HTML 和 TypeScript 代码编译成高效的 JavaScript 代码,之后浏览器就可以下载并快速运行这些代码。 This guide explains how to build with the AOT compiler using different compiler options and how to write Angular metadata that AOT can compile. 本章描述了如何使用 AOT 编译器,以及如何书写能被 AOT 编译的 Angular 元数据。
Watch compiler author Tobias Bosch explain the Angular Compiler at AngularConnect 2016. 观看编译器作者 Tobias Bosch 在 AngularConnect 2016 大会里,对Angular 编译器的演讲。
{@a overview} ## Angular compilation ## Angular 中的编译 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_. Angular offers two ways to compile your application: 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: 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). 要了解更多,请参见[CLI 文档](https://github.com/angular/angular-cli/wiki),特别是[`build` 这个主题](https://github.com/angular/angular-cli/wiki/build)。
{@a why-aot} ## Why compile with AOT? ## 为什么需要 AOT 编译? *Faster rendering* **渲染得更快** 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. 使用 AOT,浏览器下载预编译版本的应用程序。 浏览器直接加载运行代码,所以它可以立即渲染该应用,而不用等应用完成首次编译。 *Fewer asynchronous requests* **需要的异步请求更少** The compiler _inlines_ external HTML templates and CSS style sheets within the application JavaScript, eliminating separate ajax requests for those source files. 编译器把外部 HTML 模板和 CSS 样式表内联到了该应用的 JavaScript 中。 消除了用来下载那些源文件的 Ajax 请求。 *Smaller Angular framework download size* **需要下载的 Angular 框架体积更小** 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. 如果应用已经编译过了,自然不需要再下载 Angular 编译器了。 该编译器差不多占了 Angular 自身体积的一半儿,所以,省略它可以显著减小应用的体积。 *Detect template errors earlier* **提早检测模板错误** The AOT compiler detects and reports template binding errors during the build step before users can see them. AOT 编译器在构建过程中检测和报告模板绑定错误,避免用户遇到这些错误。 *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. AOT 编译远在 HTML 模版和组件被服务到客户端之前,将它们编译到 JavaScript 文件。 没有模版可以阅读,没有高风险客户端 HTML 或 JavaScript 可利用,所以注入攻击的机会较少。 {@a compiler-options} ## Angular Compiler Options You can control your app compilation by providing template compiler options in the `tsconfig.json` file along with the options supplied to the TypeScript compiler. The template compiler options are specified as members of `"angularCompilerOptions"` object as shown below: ```json { "compilerOptions": { "experimentalDecorators": true, ... }, "angularCompilerOptions": { "fullTemplateTypeCheck": true, "preserveWhitespaces": true, ... } } ``` ### *skipMetadataEmit* This option tells the compiler not to produce `.metadata.json` files. The option is `false` by default. `.metadata.json` files contain infomration needed by the template compiler from a `.ts` file that is not included in the `.d.ts` file produced by the TypeScript compiler. This information contains, for example, the content of annotations (such as a component's template) which TypeScript emits to the `.js` file but not to the `.d.ts` file. This option should be set to `true` if using TypeScript's `--outFile` option, as the metadata files are not valid for this style of TypeScript output. It is not recommeded to use `--outFile` with Angular. Use a bundler, such as [webpack](https://webpack.js.org/), instead. This option can also be set to `true` when using factory summaries as the factory summaries include a copy of the information that is in the `.metadata.json` file. ### *strictMetadataEmit* This option tells the template compiler to report an error to the `.metadata.json` file if `"skipMetadataEmit"` is `false` . This option is `false` by default. This should only be used when `"skipMetadataEmit"` is `false` and `"skipTemplateCodeGen"` is `true`. It is intended to validate the `.metadata.json` files emitted for bundling with an `npm` package. The validation is overly strict and can emit errors for metadata that would never produce an error when used by the template compiler. You can choose to suppress the error emitted by this option for an exported symbol by including `@dynamic` in the comment documenting the symbol. It is valid for `.metadata.json` files to contain errors. The template compiler reports these errors if the metadata is used to determine the contents of an annotation. The metadata collector cannot predict the symbols that are designed to use in an annotation, so it will preemptively include error nodes in the metadata for the exported symbols. The template compiler can then use the error nodes to report an error if these symbols are used. If the client of a library intends to use a symbol in an annotation, the template compiler will not normally report this until the client uses the symbol. This option allows detecting these errors during the build phase of the library and is used, for example, in producing Angular libraries themselves. ### *skipTemplateCodegen* This option tells the compiler to suppress emitting `.ngfactory.js` and `.ngstyle.js` files. When set, this turns off most of the template compiler and disables reporting template diagnostics. This option can be used to instruct the template compiler to produce `.metadata.json` files for distribution with an `npm` package while avoiding the production of `.ngfactory.js` and `.ngstyle.js` files that cannot be distributed to `npm`. ### *strictInjectionParameters* When set to `true`, this options tells the compiler to report an error for a parameter supplied whose injection type cannot be determined. When this value option is not provided or is `false`, constructor parameters of classes marked with `@Injectable` whose type cannot be resolved will produce a warning. *Note*: It is recommended to change this option explicitly to `true` as this option will default to `true` in the future. ### *flatModuleOutFile* When set to `true`, this option tells the template compiler to generate a flat module index of the given file name and the corresponding flat module metadata. Use this option when creating flat modules that are packaged similarly to `@angular/core` and `@angular/common`. When this option is used, the `package.json` for the library should refer to the generated flat module index instead of the library index file. With this option only one `.metadata.json` file is produced that contains all the metadata necessary for symbols exported from the library index. In the generated `.ngfactory.js` files, the flat module index is used to import symbols that includes both the public API from the library index as well as shrowded internal symbols. By default the `.ts` file supplied in the `files` field is assumed to be library index. If more than one `.ts` file is specified, `libraryIndex` is used to select the file to use. If more than one `.ts` file is supplied without a `libraryIndex`, an error is produced. A flat module index `.d.ts` and `.js` will be created with the given `flatModuleOutFile` name in the same location as the library index `.d.ts` file. For example, if a library uses `public_api.ts` file as the library index of the module, the `tsconfig.json` `files` field would be `["public_api.ts"]`. The `flatModuleOutFile` options could then be set to, for example `"index.js"`, which produces `index.d.ts` and `index.metadata.json` files. The library's `package.json`'s `module` field would be `"index.js"` and the `typings` field would be `"index.d.ts"`. ### *flatModuleId* This option specifies the preferred module id to use for importing a flat module. References generated by the template compiler will use this module name when importing symbols from the flat module. This is only meaningful when `flatModuleOutFile` is also supplied. Otherwise the compiler ignores this option. ### *generateCodeForLibraries* This option tells the template compiler to generate factory files (`.ngfactory.js` and `.ngstyle.js`) for `.d.ts` files with a corresponding `.metadata.json` file. This option defaults to `true`. When this option is `false`, factory files are generated only for `.ts` files. This option should be set to `false` when using factory summaries. ### *fullTemplateTypeCheck* This option tells the compiler to enable the [binding expression validation](#binding-expresion-validation) phase of the template compiler which uses TypeScript to validate binding expressions. This option is `false` by default. *Note*: It is recommended to set this to `true` as this option will default to `true` in the future. ### *annotateForClosureCompiler* This option tells the compiler to use [Tsickle](https://github.com/angular/tsickle) to annotate the emitted JavaScript with [JsDoc](http://usejsdoc.org/) comments needed by the [Closure Compiler](https://github.com/google/closure-compiler). This option defaults to `false`. ### *annotationsAs* Use this option to modify how the Angular specific annotations are emitted to improve tree-shaking. Non-Angular annotations and decorators are unnaffected. Default is `static fields`. value | description ----------------|------------------------------------------------------------- `decorators` | Leave the Decorators in-place. This makes compilation faster. TypeScript will emit calls to the __decorate helper. Use `--emitDecoratorMetadata` for runtime reflection. However, the resulting code will not properly tree-shake. `static fields` | Replace decorators with a static field in the class. Allows advanced tree-shakers like [Closure Compiler](https://github.com/google/closure-compiler) to remove unused classes. ### *trace* This tells the compiler to print extra information while compiling templates. ### *enableLegacyTemplate* The use of `