MinSafe Angular

Minification is often used to decrease the size of JS files, consequently decreasing load times.

Many minification tools rename variables to single characters. For example a minification tool will take the following code block:

function sayHi (name) {
  console.log("Hi " + name);
}

sayHi("Dave");

..and change it to:

// note: the only minification task shown in the examples on this page is the
// renaming of variables

function sayHi (a) {
  console.log("Hi " + a);
}

sayHi("Dave");

This can cause problems with Angular dependency injection. A common way of injecting dependencies is to pass the dependency names as function arguments:

angular.module("myApp")
  .controller("MyCtrl", function ($location) {
    var path = $location.path();
    console.log("This page is located at " + path);
  });

..becomes:

angular.module("myApp")
  .controller("MyCtrl", function (a) {
    var b = a.path();  // undefined
    console.log("This page is located at " + b)
  });

To ensure minification does not break an Angular app, Inline Array Notation must be to ensure that the dependency injection will be successful regardless of the name of the function’s parameter:

angular.module("myApp")
  .controller("MyCtrl", ["$location", function (locationVar) {
    var path = locationVar.path();
    console.log("This page is located at " + path);
  }]);

// after variables are renamed:

angular.module("myApp")
  .controller("MyCtrl", ["$location", function (a) {
    var b = a.path();  // (= this works
    console.log("This page is located at " + b)
  }]);

If you want to save yourself from writing extra lines of code, you can forget the Inline Array Notation and use ngmin to make your Angular code minsafe before minifying it.