Angular 1.x Minification

January 17, 2017 by JavaScript   Angular  

Undoubtedly if you've ever worked with an Angular 1.x project and attempted to minify your project, you would have ran into some difficulties.

Now surely I don't need to explain the virtues of minification, but for record purposes, let me list some.

  • Reduced bandwidth consumption
  • Reduced number of HTTP requests (when combining minified files)
  • Faster downloads of resources

But, what is the "difficulties" I am referring to?

Angular 1.x makes use of string-dependent dependency injection, have a look at the following snippet.

angular.module('app').controller('someController', function($scope) {
	$scope.text = 'Hello Mars';  

Have a look at what happens after typical minification is applied to the script.

angular.module('app').controller("someController",function(a){a.text="Hello Mars"});

You will notice that the $scope argument (among other things) is renamed to "a", from a string-dependent dependency injection point of view this is horrible, since there is no way to resolve the dependency anymore.

Unknown provider: aProvider <- a <- someController
Obviously (using a minifier that is worth its salt) we can disable mangling (renaming of variables and functions), but by doing so we will loose some of the bandwidth gains.

Luckily there are alternative ways to annotate dependencies, which will not be affected by minification.

  • Array annotation

    angular.module('app').controller('someController', ['$scope', function($scope) {
    	$scope.text = 'Hello Mars';  

  • $inject property annotation

    someController.$inject = ['$scope'];
    function someController($scope) {
    	$scope.text = 'Hello Mars';  
    angular.module('app').controller('someController', someController);

The only crappy thing (minus the annoyance of annotating like this) is that deriving dependencies implicitly from function parameters names will still be the order of the day, which becomes quite a bit of a pain seeing that one will only notice a dependency issue pre-minification.

Initially when I was planning to write this post, I was going to share an elaborate script I wrote which points out missing annotations during runtime, luckily there is a better way.

By including ng-strict-di to your html template, explicit annotations will be required post-minification as well.

<html ng-app="app" ng-strict-di>

Instead of getting that ugly "unknown provider" error message in your console pre-minification, you will get something like this, post-minification.

someController is not using explicit annotation and cannot be invoked in strict mode
Thats pretty much the just of it.

Leave a Comment