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.

 

 
Sie wollen mehr zum Thema Using Angular and AOT with Webpack wissen? Hier können Sie eine Anfrage für eine unverbindliche Schulung ode Beratung bzw. einen Workshop erstellen.
 
Unverbindliche Anfrage
 
 

Schulung und Beratung

Angular 2

Datenbindung, Formulare, Validierung, Routing, HTTP, Komponenten, ...

Details

Angular 2: Advanced

Erweiterte Aspekte von Angular 2

Details

Reaktive Architekturen mit Angular und Redux

Dieses interaktive Seminar vermittelt, wie Sie reaktive Anwendungen mit Angular entwickeln können.

Details

Migration von AngularJS 1.x auf Angular 2

Bestehende Projekte auf Angular 2 migrieren, ngUpgrade, ...

Details

Angular 2 Review

Feedback und klärung offener Fragen, weiterführende Themen

Details

Angular 2 Workshop

Start ohne Umwege

Details

Weitere Schulungen ...