Skip to main content

ASP.NET MVC Enabling Bundling and Minification

Anyone who has worked on implementing ASP.NET MVC bundling and minification within their project should be familiar with how it is setup. It is essentially controlled by two configuration, one within the context of your code i.e.

BundleTable.EnableOptimizations = true;

Another configuration is setup in your web.config i.e.

<compilation debug="true" />

By default, the compilation debug mode is set to true on your local environment. However, during deployment to a production or production like environment, your release web.config transformation should have turned that to false.

The only time the compilation debug mode matters in the context of bundling and minification would be when you don't use the code to enable bundling and minification. You can simply rely on the web.config to turn bundling and minification on or off by setting debug to be false or true respectively.

So, you might be thinking to simply just enable optimization by code and be done with it. Actually, it depends. The reason is that when you enable bundling and minification, you lose the ability to debug your custom javascript file. In Visual Studio, you have the ability to bundle your custom javascript files like so:

bundles.Add(new ScriptBundle("~/bundles/my").Include("~/Scripts/My/*.js"));

You can set breakpoints within your javascript file and be able to debug. However, if you always enable bundling and minification, your javascript file would not be loaded at all since it is bundled and minified.

We can also consider adding the following syntax where optimizations would always be enabled in release mode. This way, you still get to debug your local javascript file and be able to enjoy benefit of enabling bundling and minification when released.

#if DEBUG
            BundleTable.EnableOptimizations = false;
#else
            BundleTable.EnableOptimizations = true;
#endif


This is equivalent to the solution of setting the changes in the compilation debug mode of false. However, note that when compilation debug mode is set to false, you can no longer debug in visual studio on all your code.

In a different situation, if you decide that you do want to test out bundling and minification and still be able to debug, then simply setting enable optimization to be true in code would satisfy your need.

By understanding the behaviors in using both types of configurations or just one, we can understand the potential pros and cons of each, and in the end, we can employ the right technique.

Comments