Do you name your dependencies to avoid problems with minification?

Last updated by Tiago Araújo [SSW] about 1 year ago.See history

Angular uses parameter names to determine which dependencies to inject. When you minify your angular code, the parameter names are changed, so you must name your dependencies to ensure they work correctly.

The standard way to inject your dependencies looks a little like the following. We're defining a controller in this case.

phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {...}

Code: Bad example - This code will break when minified

When this code is minified the parameters are renamed. This means that the dependency injector no longer knows which services to inject.

You can fix this in 2 ways. The first one uses the $inject property to identify the name of the parameters in order:

function PhoneListCtrl($scope, $http) {...}
PhoneListCtrl.$inject = ['$scope', '$http'];
phonecatApp.controller('PhoneListCtrl', PhoneListCtrl);

Code: Good example - This code names the parameters using the $inject property

The second and preferred option is to pass an array containing the names, followed by the function itself. Take a look:

phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', function($scope, $http) {...}]);

Code: Better example - This code names the parameters inline which is a little cleaner

Using this method will ensure you don't run into problems with minification. If you'd like to know more, check out the Angular tutorial for Dependency Injection.

We open source. Powered by GitHub