Question

I'm trying to minify and bundle my AngularJS/WebAPI Project in Visual Studio 2013. When I run my project after minifying I get an error like this:

Error: [$injector:modulerr] http://errors.angularjs.org/1.2.13/$injector/modulerr?p0=app&p1=%5B%24injector%3Aunpr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.2.13%2F%24injector%2Funpr%3Fp0%3Dn%0Av%2F%3C%40http%3A%2F%2Flocalhost%3A63389%2Fbundles%2Fangular%3Fv%3D_ykkA4necF0i5wrX1pYwFxAqwK5bvRGCF4SEL-Meqac1%3A1%0Ane%2Fu.%24injector%3C%40http%3A%2F

From the reading I've done it sounds like Angular has trouble with injection after minifying code. I'm trying to figure out if there is a 'best practice/workflow' for debugging this inside Visual Studio. How do I make sense of the error above?

Was it helpful?

Solution

The only problem I've seen with minifying AngularJs App is with the function parameter injection syntax. Like:

app.config(function($serviceA, $serviceB) { ... });

When minifying, function parameter might be changed to a shorter name. So this might become:

app.config(function(a, b) { ... });

Which is unknown. You should always (I haven't seen a bad case for it yet..) use the array injection syntax:

app.config(['$serviceA', '$serviceB', function($serviceA, $serviceB) { ... }]);

The function parameters will get minified, but string constant don't, which allow Angular to know the name of the service you are asking, regardless of the function parameter name.

OTHER TIPS

I learned the best solution is not to use ASP.NET MVC minifying but to use Grunt with ng-annotate. This will decorate the AngularJS controllers and minify them. It will take a little time to learn but is worth it. I can provide a sample of a Grunt script if you find this usefully.

You need to annotate your code as Visual Studio minify changes $scope and other variables.

Change from

var MyController = function($scope, $http) { ..  }

to

var MyController = ['$scope', '$http', function($scope, $http) { .. }]

References: http://weblogs.asp.net/dwahlin/structuring-angularjs-code and Angularjs minify best practice

The Angular Documention has a note on this...

Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for PhoneListCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.

Example :

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', ['$scope', '$http',
  function ($scope, $http) {
    $http.get('phones/phones.json').success(function(data) {
      $scope.phones = data;
    });

    $scope.orderProp = 'age';
  }]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top