Using Angular And AOT With Webpack

Using Angular And AOT With Webpack

The Angular CLI provides AOT compilation out of the box. To make use of it, just create a production build:

ng build --prod

Under the hoods, the CLI uses the package @ngtools/webpack which provides a loader for compiling TypeScript as well as a Plugin for AOT. One can easily use these mechanisms directly with webpack. The easiest way to do this is to create a project with the CLI and then eject the CLI. Ejecting means that the CLI is blasted away and instead of this webpack is used directly:

ng eject

If there is an existing webpack configuration it can also be extended by the mentioned mechanisms quite easily. First of all, install the @ngtools/webpack package:

npm i @ngtools/webpack --save-dev

If the usage of @ngtools/webpack yields errors one should check the referenced Angular version. In general, this packages works best with the version the CLI is using currently. Other versions could cause issues.

After this, TypeScript files can be loaded with the @ngtools/webpack loader:

module: {
    rules: [
        { test: /\.ts$/, loaders: ['@ngtools/webpack']}

For AOT, just add the AOT 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

One very nice side effect of this is, that you don't have to write an own file to bootstrap Angular in AOT mode. Instead of this the Plugin is generating the code necessary for this.