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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Unless you need this data elsewhere I would do it right before the compiling of the includes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.