Search code examples
c#css.netasp.net-mvcbundling-and-minification

Bundling not working in MVC5 when I turn on release mode


I have the following bundle configured in BundleConfig.cs:

bundles.Add(new StyleBundle("~/bundles/css").Include(
                      "~/assets/bootstrap/css/bootstrap.css",
                      "~/assets/css/global/all.css"));

and I reference it using the following:

@Styles.Render("~/bundles/css")

When I'm in debug mode (web.config compilation debug="true") it works as expected in that it renders both css files as normal ie:

<link href="/assets/bootstrap/css/bootstrap.css" rel="stylesheet"/>
<link href="/assets/css/global/all.css" rel="stylesheet"/>

However when I set debug="false" the above behaviour still occurs in that it does recognise the files, however it's just rendering them as normal.

To confirm bundling can definitely work I've enabled optimizations in BundleConfig ie BundleTable.EnableOptimizations = true;

Whenever I do the above, it bundles the css and appears as expected ie:

<link href="/bundles/css?v=WBKHkZAJly7jUzHrVDT8SwfaQE-CA9dbOUQUlLKadNE1" rel="stylesheet"/>

EDIT:

A few people have mentioned that adding the following code to my BundleConfig.cs file will achieve what I am after:

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

I understand and appreciate this response, however according to the documentation, the default behaviour of MVC bundling is to bundle in release mode but not in debug mode. I don't see why I should need to add extra code to make it do this when it should be doing it already.

EDIT 2

I've a confession to make. It turns out I had the web.config from the Views folder opened and not the main web.config. I changed the setting in the main web.config and this works just fine for me. I blame ReSharper


Solution

  • This is the default behavior.

    Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element in the Web.config file.

    <system.web>
        <compilation debug="true" />
        <!-- Lines removed for clarity. -->
    </system.web>
    

    To enable bundling and minification, set the debug value to "false". You can override the Web.config setting with the EnableOptimizations property on the BundleTable class. The following code enables bundling and minification and overrides any setting in the Web.config file.

    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                     "~/Scripts/jquery-{version}.js"));
    
        // Code removed for clarity.
        BundleTable.EnableOptimizations = true;
    }
    

    http://www.asp.net/mvc/overview/performance/bundling-and-minification

    enter image description here