The Angular CLI ships with AOT compilation enabled by default. All that’s required is a production build:
ng build --prod
Internally, the CLI relies on the package @ngtools/webpack, which includes both a TypeScript compilation loader and a Plugin dedicated to AOT. These tools can be wired straight into a custom webpack setup without much effort. The simplest approach is to scaffold a project with the CLI and then eject it — a process that removes the CLI and leaves webpack as the direct build tool:
ng eject
For projects that already have a webpack configuration in place, integrating these mechanisms is straightforward. Start by installing the @ngtools/webpack package:
npm i @ngtools/webpack --save-dev
Should the use of @ngtools/webpack produce errors, check which Angular version is being referenced. Generally, this package performs best when matched with the version currently used by the CLI; other combinations may lead to problems.
Once that’s done, TypeScript files can be processed with the @ngtools/webpack loader:
module: {
rules: [
[...]
{ test: /\.ts$/, loaders: ['@ngtools/webpack']}
],
},
Enabling AOT is then simply a matter of adding the plugin:
var AotPlugin = require('@ngtools/webpack').AotPlugin;
[...]
plugins: [
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: 'app/app.module#AppModule'
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
output: {
comments: false
},
sourceMap: false
}),
[...]
}
A notable benefit here is that there’s no need to write a separate file for bootstrapping Angular in AOT mode; the plugin automatically generates the necessary code for this task.
