1

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?

Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
Bobby B
  • 2,287
  • 2
  • 24
  • 47

1 Answers1

3

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.

Community
  • 1
  • 1
Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
  • Where would you perform the check for the `IsDebuggingEnabled`? The bundling system is initially registered in the `global.asax.cs` I think, so would you do it there? Is the context already alive that early in the pipeline? – Bobby B Dec 12 '12 at 14:29
  • Unless you need this data elsewhere I would do it right before the compiling of the includes. – Levi Botelho Dec 12 '12 at 14:32