Search code examples
c#asp.net-mvc-4visual-studio-debuggingasp.net-optimizationbundling-and-minification

Bundling css/js only in debug mode


Is there a way to make MVC4's bundling system include scripts/styles only in debug mode?

For example, I have lots of debug mode scripts which help me debug my system. I obviously don't want them rendered when the system is in release mode.

I thought of using a block like:

  bundles.Add(
    new ScriptBundle("mybundle")
    .Include(
      "~/scripts/foo.js",
      "~/scripts/bar.js"
      #if DEBUG
      ,"~/scripts/baz-debug.js"
      #endif
    )
  );

but debug mode should be controlled via web.config.

So what is the correct approach?


Solution

  • To check if debugging is enabled you can use this:

    HttpContext.Current.IsDebuggingEnabled
    

    provided that the HttpContext is accessible. If not, the longer approach would be this one:

    var isDebug =(System.Web.Configuration.CompilationSection)ConfigurationManager.GetSection("system.web/compilation").Debug;
    

    Both these suggestions come from this article: How do I check if Debug is enabled in web.config.

    What I would do to actually add modules conditionally would be to start off by creating a Dictionary<string, bool> of script paths and whether or not they should be added in release mode.

    When you call the program, if debugging is false then simply filter the dictionary into a collection of elements:

    var includes = dict.Where(x => x.Value).Select(x => x.Key);
    

    And then pass the result to your Include statement.