# The Ahead-of-Time (AOT) Compiler # 预先(AOT)编译 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 应用由大量组件及其 HTML 模板组成。 在浏览器渲染应用之前,组件和模板必须由 *Angular 编译器*转换成可执行的 JavaScript 代码。 Angular offers two ways to compile your application: Angular 提供了两种方式来编译你的应用: 1. **_Just-in-Time_ (JIT)**, which compiles your app in the browser at runtime **即时(JIT)编译**,它会在浏览器中运行时编译你的应用 1. **_Ahead-of-Time_ (AOT)**, which compiles your app at build time. **预先(AOT)编译**,它会在构建时编译你的应用。 JIT compilation is the default when you run the _build-only_ or the _build-and-serve-locally_ CLI commands: 当你运行 *`build`* 或 *`serve`* 这两个 CLI 命令时 JIT 编译是默认选项: 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: 要进行 AOT 编译只要给这两个 CLI 命令添加 `--aot` 标志就行了: ng build --aot ng serve --aot
The `--prod` meta-flag compiles with AOT by default. `--prod` 标志也会默认使用 AOT 编译。 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 ## Angular 编译器选项 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: 你可以通过在 `tsconfig.json` 文件中随 TypeScript 编译选项一起提供模板编译选项来控制应用的编译方式。 这些模板编译选项都是作为 `"angularCompilerOptions"` 对象的成员指定的,代码如下: ```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` 文件,它默认是 `false`。 `.metadata.json` files contain information 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. `.metadata.json` 文件中包含模板编译器所需的信息,这些信息来自于 `.ts` 文件中,但是没有包含在由 TypeScript 编译器生成的 `.d.ts` 文件中。 比如,这个信息包括 TypeScript 发出的注解内容(如组件的模板),TypeScript 把它生成到了 `.js` 文件中,但是没有生成到 `.d.ts` 文件中。 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. 如果使用了 TypeScript 的 `--outFile` 选项,那就要同时设置这个选项。因为在 TypeScript 的这种输出方式下,metadata 文件是无效的。 Angular 中不建议使用 `--outFile`,请改用 [webpack](https://webpack.js.org/) 之类的打包器代替。 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. 当使用工厂汇总器(factory summary)时,这个选项也要设置为 `true`,因为工厂汇总器在自己的 `.metadata.json` 中也包含了这些信息的一个副本。 ### *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`. 这个选项告诉模板编译器如果 `"skipMetadataEmit"` 为 `false`,那就把错误信息汇报到 `.metadata.json` 中。 只有当 `"skipMetadataEmit"` 为 `false` 且 `"skipTemplateCodeGen"` 为 `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. 它的设计意图是要验证为打包 `npm` 而生成的 `.metadata.json` 文件。 这种验证过于严格,在使用模板编译器时甚至可能会对那些铁定不会出错的元数据文件报告一些错误。 你可以用 `@dynamic` 在注释中指定一些要导出的符号,来禁止对它们报告错误。 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. 对于 `.metadata.json` 文件来说,包含错误是正常的。如果这些元数据被用来确定注解的内容,模板编译器就会报告这些错误。 元数据收集器无法判断这些符号的设计目的是用在注解中,所以它将会自作主张,在元数据中为这些导出的符号添加错误节点。 如果这些符号被用到了,模板编译器就会根据这些错误节点报告错误。 如果某个库的使用者只是在注解中(而不是普通代码中)使用这些符号,模板编译器通常不会报错。 这个选项允许在该库(比如 Angular 自身这些库)的构建和使用过程中检测这类错误。 ### *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`. 这个选项告诉编译器忽略从 `.ngfactory.js` 和 `.ngstyle.js` 文件中发出的错误。 如果为 `true`,它就会关闭大多数的模板编译器,并禁止汇报模板诊断信息。 这个选项用于指示模板编译器为通过 `npm` 包分发而生成 `.metadata.json` 文件,同时避免生成无法分发到 `npm` 的 `.ngfactory.js` 和 `.ngstyle.js` 文件。 ### *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. 当设置为 `true` 时,该选项会告诉编译器为那些无法确定其类型的注入参数报告错误。 当该值没有提供或未 `false` 时,那些带有 `@Injectable` 的类,如果其构造参数的类型无法解析,就会生成一个警告。 *Note*: It is recommended to change this option explicitly to `true` as this option will default to `true` in the future. *注意*:建议把该选项显式改为 `true`,因为将来这个选项的默认值会是 `true`。 ### *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. 当为 `true` 时,该选项告诉模板编译器生成一个指定名字的扁平模块索引和相应的扁平模块元数据。 当要创建像 `@angular/core` 和 `@angular/common` 这样的扁平模块包时,请使用本选项。 当使用本选项时,库的 `package.json` 文件就会引用生成的扁平模块索引,而不是库的索引文件。 当使用本选项时,只会生成一个 `.metadata.json` 文件,其中包含从库索引中导出的符号所需的全部元数据。 在生成的 `.ngfactory.js` 文件中,扁平模块索会用来导入包括库的公共 API 和隐藏的内部符号在内的全部符号。 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"`. 默认情况下,`files` 字段中提供的 `.ts` 文件会被当做库索引。 如果指定了多个 `.ts` 文件,就要用 `libraryIndex` 来选择要作为库索引的文件。 扁平模块索引会用 `flatModuleOutFile` 中给出的名字创建 `.d.ts` 和 `.js` 文件,并放在和库索引的 `.d.ts` 文件相同的位置。 比如,如果某个库使用 `public_api.ts` 文件作为该模块的库索引,那么 `tsconfig.json` 的 `files` 字段就应该是 `["public_api.ts"]`。 然后可以把 `flatModuleOutFile` 选项设置为 `"index.js"`,它就会生成 `index.d.ts` 和 `index.metadata.json` 文件。 该库的 `package.json` 文件的 `module` 字段将会是 `"index.js"`,而 `typings` 字段会是 `"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. 该选项指定建议的模块 ID,这个 ID 用于导入扁平模块。 从扁平模块中导入符号时,由模板编译器生成的引用将使用这个模块名称。 它仅在同时提供了 `flatModuleOutFile` 选项时才有意义,否则,编译器将忽略此选项。 ### *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. 这个选项告诉模板编译器也为与 `.metadata.json` 文件对应的 `.d.ts` 文件生成工厂文件(`.ngfactory.js` 和 `.ngstyle.js`)。 这个选项默认为 `true`。当该选项为 `false` 时,只会为 `.ts` 文件生成工厂文件。 This option should be set to `false` when using factory summaries. 当使用工厂汇总器时,这个选项应该设置为 `false`。 ### *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. 该选项告诉编译器要为模板编译器启用[绑定表达式验证](#binding-expresion-validation)阶段,它会使用 TypeScript 来验证绑定表达式。 This option is `false` by default. 该选项默认是 `false`。 *Note*: It is recommended to set this to `true` as this option will default to `true` in the future. *注意*:建议把它设置为 `true`,因为将来它会默认为 `true`。 ### *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`. 该选项告诉编译器使用 [Tsickle](https://github.com/angular/tsickle) 来为生成的 JavaScript 添加供 [Closure Compiler](https://github.com/google/closure-compiler) 使用的 [JsDoc](http://usejsdoc.org/) 注解。 该选项默认为 `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`. 使用这个选项来修改生成 Angular 特有注解的方式,以提升摇树优化(tree-shaking)的效果。它对 Angular 自身之外的注解和装饰器无效。 默认值是 `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. 原地保留装饰器。这会让编译过程更快。TypeScript 将会生成对 `__decorate` 助手函数的调用。使用 `--emitDecoratorMetadata` 进行运行时反射。不过,生成的代码将无法正常进行摇树优化。 `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.使用类的静态字段代替装饰器。它允许像 [Closure Compiler](https://github.com/google/closure-compiler) 这样的高级摇树优化器移除未使用的类。 ### *trace* This tells the compiler to print extra information while compiling templates. 它告诉编译器在编译模板时打印额外的信息。 ### *enableLegacyTemplate* The use of `