ASP.NET MVC 4 app with bundling and minification, why is minification enabled in debug mode

asp.net-mvc-4asp.net-optimizationbundling-and-minification

I've just migrated an ASP.NET MVC 3 project to MVC 4 / .NET 4.0, and installed NuGet package Microsoft.AspNet.Web.Optimization in order to support bundling and minification of CSS and JavaScript. I've pretty much got bundling/minification working, the problem is it's always enabled. Even though the app is in debug mode, as configured in Web.config, all JavaScript includes are minified. As you can see from the below XML snippet, debug mode is enabled in Web.config:

<system.web>
  <compilation debug="true" targetFramework="4.0">
    ...
  </compilation>
  ...
</system.web>

An excerpt of my bundle configuration:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        ...

        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-1.*",
                    "~/Scripts/jquery.form.js",
                    "~/Scripts/jquery.format.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
            "~/Content/Site.css"));

        ...
    }
}

CSS/JavaScript includes are rendered in the HTML as for example:

<link href="/content/css" rel="stylesheet" type="text/css">
<script src="/bundles/jquery" type="text/javascript"></script>

Does anyone have any clue as to why minification gets enabled in my case? I am at a loss as to what I'm missing here. To troubleshoot I created a test ASP.NET MVC 4 Internet application and could verify that CSS/JavaScript did not get minified in debug mode for this project.

EDIT:

In my _Layout.cshtml file I render the styles/scripts like this:

@Styles.Render("content/css")
@Scripts.Render("bundles/jquery")

Thanks to Hao, I realize that I've forgot to prefix the bundle names with "~/".

Best Answer

The red flag is with the link/script tags rendered in your HTML:

These should contain a version hashcode if you are using Script/Style.Render, i.e.

< script src="/bundles/jquery?v=wvLq7H7qEZB2giyIRn7aEZAxhHOb2RfTYYh2HMd9EqM1"/>

To get the debug/release behavior that the MVC4 templates are using, you must use the Script/Style.Render methods as well. When calling these methods, you must pass virtual bundle paths, in your example:

@Styles.Render("~/content/css")
@Scripts.Render("~/bundles/jquery")

In debug mode, you should not get link/script tags pointing at the bundle (which will always be minified/bundled). Instead you should be getting script/link tags to the individual resources in debug mode.

Related Topic