In this post I will show how to use @angular-devkit/build-optimizer to further optimize Angular Webpack builds.

Build-Optimizer (PurifyPlugin) is a Webpack plugin created by the Angular team, specifically to optimize Webpack builds beyond what Webpack can do on its own.

One example of this is removal of Angular decorators from AoT builds.

Decorators like @Component are not needed when doing AoT builds since the compiler extracts all necessary information from the decorator during compilation.

There is potential for a sizable size reduction from removing @Component, especially if you have large inline templates in your components.

Another example of optimization is adding /*@__PURE__*/ annotations to transpiled/downleveled TypeScript classes. The point of this is to make it easier for minfiers like Uglify to remove unused code.

You can see the full list of optimizations here.

Experiment

I decided to run the purify plugin against one of my existing applications to measure the effect.

The baseline for the experiment is a medium size Angular application (111k bundle size).

Result

Results will obviously vary per application, but most application should at least benefit “some” from this.

In my case the bundle size shrunk to 97.7k (12%).

Considering the low effort involved in enabling the plugin, 12% seems like a pretty good result here.

I have included my Webpack config below. The key to this is adding the PurifyPlugin, as well as the @angular-devkit/build-optimizer/webpack-loader.

const webpack = require('webpack'); const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin'); const PurifyPlugin = require('@angular-devkit/build-optimizer').PurifyPlugin; module.exports = { entry: './built-es5/app/main.js', output: { filename: 'dist/bundle-webpack-3-no-lazy-loading.js' }, module: { rules: [ { test: /\.js$/, loader: '@angular-devkit/build-optimizer/webpack-loader', options: { sourceMap: false } } ] }, plugins: [ new webpack.optimize.ModuleConcatenationPlugin(), new UglifyJsPlugin({ beautify: false, output: { comments: false }, mangle: { screw_ie8: true }, compress: { screw_ie8: true, warnings: false, conditionals: true, unused: true, comparisons: true, sequences: true, dead_code: true, evaluate: true, if_return: true, join_vars: true, negate_iife: false }, }), new PurifyPlugin() ] }