27
votes

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.

3
Technically a duplicate of stackoverflow.com/questions/13032721/…, although I don't think the answer makes sense.drzaus
This question also duplicated by stackoverflow.com/questions/17410012/…drzaus

3 Answers

46
votes

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
}]);
1
votes

if you still want to control what to minify and what not (or if you want to include an already minified version by the plugin vendor) just declare two bundles, and only minify one of them on your BundleConfig.cs:

var dontMinify = new Bundle("~/bundles/toNotMinify").Include(
                        "~/Scripts/xxxxx.js");
bundles.Add(dontMinify);

var minify = new Bundle("~/bundles/toNotMinify").Include(
                        "~/Scripts/yyyyyy.js");
minify.Transforms.Add(new JsMinify());
bundles.Add(minify);
1
votes

For those of you who don't want/can't be arsed to write the "minification-safe" angular-DI syntax, and don't care about variable names being obfuscated, I used BundleTransfomer along with Yui Js minifier - available via nuget:

 Install-Package BundleTransformer.Core
 Install-Package BundleTransformer.Yui

Gives VERY fine-grained control over minification/obfuscation. In the angular world, just set the obfuscateJavascript within the yui web.config section to false.