asp.netwebformsweb-optimizationbundletransformer

Disabling JS/CSS bundling if debug=true in Web.config


I am using BundleTransformer to bundle and minify JS/CSS in a legacy ASP.NET WebForms app. However, I'd like to disable bundling if <compilation debug="true"> in Web.config.

Is this possible?

Below is an example of how I currently create one of the bundles:

BundleConfig.cs

var jsMinifier = new BundleTransformer.JsMin.Minifiers.CrockfordJsMinifier();
var customJsTransformer = new BundleTransformer.Core.Transformers.ScriptTransformer(jsMinifier);
var CustomJsBundle = new BundleTransformer.Core.Bundles.CustomScriptBundle("~/bundles/CustomJsBundle");

foreach (var item in jsFiles)
{
    CustomJsBundle.Include(item);
}

CustomJsBundle.Transforms.Clear();
CustomJsBundle.Transforms.Add(customJsTransformer);
BundleTable.Bundles.Add(CustomJsBundle);

Navigation.master

<%@ Master Language="C#" CodeFile="Navigation.master.cs" Inherits="Main_Nav" %>
<%@ Import Namespace= "System.Web.Optimization" %>
<html>
    <head runat="server">
        <%= Scripts.Render("~/bundles/CustomJsBundle") %> 
        <!-- if debug=true, I'd like the server to just render references to the individual script files
        instead of the bundle -->
    </head>
    <body>
        <!-- other markup -->
    </body>
</html>

The Scripts.Render call in Navigation.master always displays a bundle, even if debug is true. I'd like it to render the bundle only if debug is false. Otherwise, I'd like script tags to each individual script file rendered instead for debugging purposes.


Solution

  • I solved this for now by using the RenderFormat method when in DEBUG mode. Otherwise, I use the usual Render method.

    For example, in my Navigation.master:

    <% #if DEBUG %>
    <%= Scripts.RenderFormat("<script src='{0}'/></script>", "~/bundles/CustomJsBundle") %>
    <% #else %>
    <%= Scripts.Render("~/bundles/CustomJsBundle") %>
    <% #endif %>
    

    This has the desired effect of:

    I'm not sure if there is a better way to do this, but if so, please comment or submit an answer. I tried other potential solutions, such as setting EnableOptimizations to false, and clearing the BundleTable, but this is the only solution that has worked.