In this post I will talk about integrating the Closure compiler with an NgUpgrade application.


NgUpgrade is a tremendous help for folks who are looking to gradually upgrade complex AngularJS applications to Angular.

The downside is that you have to run two versions of Angular in the same application.

Adding Angular to an already large AngularJS application may have a negative impact on performance since the application footprint will grow.

This means NgUpgrade applications need all the help they can get in terms of minimizing the size of the Angular bits.

Closure Compiler

What better way to shrink the footprint than adding the Closure compiler to your build?

Closure compiling pure Angular applications without external dependencies is relatively straightforward. With NgUpgrade there are a few extra things to consider though.

Configuring an NgUpgrade application requires a handshake between Angular and AngularJS.

During bootstrap, Angular will refer back to the AngularJS part of the application, and invoke AngularJS specific functions like module, directive, factory etc.

These calls are references back to global methods on the AngularJS, angular object. This means we have to shield these function names from aggressive Closure compiler name mangling. Otherwise there will be runtime issues since the shortened property names are not recognized by AngularJS.

Luckily Closure compiler has a built in mechanism for opting out of name mangling. The feature we use for this is called externs. Basically, it's nothing more than a whitelist of names that the Closure compiler will leave alone during optimization.

You basically need externs for any AngularJS feature referenced from the Angular part of your application.

It can be tedious to hand code large sets of externs, but in the case of AngularJS, we are in luck.

The Closure compiler community has already provided us the externs for mutliple versions of AngularJS. Here is an example for AngularJS 1.6.

I have created a simple example of a Closure compiled NgUpgrade application here if you are interested in checking it out. Remember to remove the --debug flag in the Closure config for the best results.