AoT Configuration

To enable AoT in Angular, there are two possible methods:

  • using ngc directly
  • using @ngtools/webpack
    We recommend the second way because it fits the Angular + Webpack toolchain the best. One problem of using raw ngc is that ngc tries to inline CSS while lacking necessary context. For example, the @import 'basscss-basic' statement in index.css would cause an error like Error: Compilation failed. Resource file not found with ngc. It lacks the information that 'basscss-basic' is actually a node module inside node_modules. On the other hand, @ngtools/webpack provides AotPlugin and loader for Webpack which shares the context with other loaders/plugins. So when ngc is called by @ngtools/webpack, it can gather necessary informations from other plugins like postcss-import to correctly understand things like @import 'basscss-basic'.

Config @ngtools/webpack

First, get @ngtools/webpack from npm and save it as a development dependency:

  1. npm install -D @ngtools/webpack

Then, inside the Webpack configuration file (usually named as webpack.config.js), add following code:

  1. import {AotPlugin} from '@ngtools/webpack'
  2. exports = { /* ... */
  3. module: {
  4. rules: [
  5. {
  6. test: /\.ts$/,
  7. loader: '@ngtools/webpack',
  8. }
  9. ]
  10. },
  11. plugins: [
  12. new AotPlugin({
  13. tsConfigPath: 'path/to/tsconfig.json',
  14. entryModule: 'path/to/app.module#AppModule'
  15. })
  16. ]
  17. }

Here @ngtools/webpack replaces other typescript loader like ts-loader or awesome-typescript-loader. It works with AotPlugin together to enable AoT compilation. More details can be found here.

(Note, for project generated by angular-cli, turning on AoT can be simple as ng build —aot, but since angular-cli does not allow customized webpack configuration for complex use cases, it may be insufficient.)

原文: https://angular-2-training-book.rangle.io/handout/aot/aot_config.html