Minification is a very important tool to reduce transmission time of code pieces.

There is a wrong and diffused use not to apply code minification and to concatenate code, obliging clients to download all JavaScript dependencies as uncompressed, separate files.     As the download number increases (often there are dozen of javascript files), latency times between files can grow dramatically. 

There are lots of support tools to deployment (Grunt, Gulp, Assetic and the likes): most of them are capable to give as output a single javascript file containing all the original files concatenated and minificated in the right order.

These very useful tools can cause side effects in AngularJS, mainly due to its function of DI (Dependency Injection).

AngularJS has two ways to declare dependencies when creating elements (e.g., a controller).

The first mode is the following:

angular.module("myApp").
  controller("myController", function($scope){
  	$scope.foo = "bar";
  });

This code perfectly works without minification. AngularJS analyzes the function code, using __toString(), and finds a "$scope" parameter inside the SC (Service Container). 

With code minification, it becomes like this:

angular.module("myApp").controller("myController",function(e){e.foo="bar"})

The minification renamed variables, so "$scope" changed to "e" and as a consequence the SC search fails.

The second mode is the following:

after minification by jcompress the code becomes like this:

angular.module("myApp").
  controller("myController", ["$scope", function($scope){
  	$scope.foo = "bar";
  }]);

When AngularJS finds as second parameter an array, it ignores the parameter name as defined in function ("e" in this case), but searches for the elements passed to the array ("$scope" in this case). The code still works after minification.

A possible solution for the first method is to use a "pre-minification" tool, responsible for rewriting the code according to the second syntax.

In the past the most used tool for this purpose was ngmin, deprecated by the author, who is now suggesting the more powerful ng-annotate. For both tools the respective integrations with the most used task runners (such as Gulp, Grunt, Broccoli) are available.

Antonello Pasella

Freelance Frontent Developer, PHP Expert , Website , Git home page , @apasella , Linkedin profile
15+ year experience in web programming, fucused on cross platform frontend and game development (even remote). Web enthusiast and game passionate, full stack programmer ready to dive into new projects. Top skills: AngularJS Phonegap PHP

All articles by Antonello Pasella

Comments

comments powered by Disqus

cloudparty

Follow Us