Mvc4 bundling, minification and AngularJS services

Matteo Mosca picture Matteo Mosca · Feb 16, 2013 · Viewed 11.5k times · Source

Is there a way to customize the way Asp.Net MVC4 bundling&minification feature minifies the js files?

Meaning, I don't want to completely turn off minification, but "as is" it just breaks AngularJs.

Since AngularJs uses DI and IoC approach for injecting services in controllers, the following:

function MyController($scope) { }

Once minified, becomes:

function MyController(n) { }

Normally that wouldn't be a problem, but AngularJs uses the parameter names to understand which service to inject. So $scope should remain $scope, as well as any other parameter in angular controllers. Everything else, like local variables, etc, should be minified normally.

I can't find any clear documentation on how to configure Mvc4 minification, and it seems rather dumb for it to be "all or nothing" so I think I'm missing something.

Thanks.

Answer

pkozlowski.opensource picture pkozlowski.opensource · Feb 16, 2013

Actually you can (and should!) write AngularJS code so it is "minification safe". Details are described in the "Dependency Annotation" section of http://docs.angularjs.org/guide/di but in short, for globally defined controllers you can write:

MyController.$inject = ['$scope'];

Please note that globally defined controllers are polluting global namespace (see this for more details) and should be avoided. If you declare a controller on a module level you can make it minification-safe as well:

angular.module('mymodule', []).controller('MyController', ['$scope', function($scope){
//controller code goes here
}]);