Search code examples
javascriptasp.net-mvc-4bundleminifyasp.net-optimization

MVC4 Beta Minification and Bundling: Ordering files and debugging in browser


I've started using bundling and minification included with the MVC4 Beta. I'm running into a few issues with it:

For one thing, if I use the classic <script src="Folder/js" type="text/javascript"/> bundling, it seems like I have to rename my files to make sure they're bundled in the proper order.

  • Let's say I have three javascript files: "ants.js", "bugs.js", "insects.js"
  • ants.js depends on bugs.js
  • bugs.js depends on insects.js
  • Default bundling seems to bundle them in alphabetical order.
  • To get them to bundle properly, I have to rename them to: "0.insects.js", "1.bugs.js", "2.ants.js"
  • That's really hackish and there has to be a cleaner way.

The next problem I'm having is debugging. I like to step through the javascript in my testing browsers, is there a way to turn off just the minification while in DEBUG mode?

EDIT: To be clear, I know I can create bundles and register them from C#, it just seems really ugly to have to do it that way.


Solution

  • To temporarily get non-minified output use this

      public class NonMinifyingJavascript : IBundleTransform
    {
        public void Process(BundleContext context, BundleResponse bundle)
        {
            if(bundle == null)
            {
                throw new ArgumentNullException("bundle");
            }
    
            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();
    
            foreach(FileInfo file in bundle.Files)
            {
                HttpContext.Current.Response.AddFileDependency(file.FullName);
            }
    
            bundle.ContentType = "text/javascript";
            //base.Process(context, bundle);
        }
    }
    

    If you wanted it based totally on a config setting, I imagine you could create an IBundle transform that delegates to this one or JsMinify depending on your config setting

    In order to control the ordering of the javascript files you need to use the BundleFileSetOrdering

     var javascriptBundle = new Bundle("~/site/js", new NonMinifyingJavascript());
    
             //controls ordering for javascript files, otherwise they are processed in order of AddFile calls
             var bootstrapOrdering = new BundleFileSetOrdering("bootstrap");
             //The popover plugin requires the tooltip plugin
             bootstrapOrdering.Files.Add("bootstrap-tooltip.js");
             bootstrapOrdering.Files.Add("bootstrap-popover.js");
             BundleTable.Bundles.FileSetOrderList.Add(bootstrapOrdering);
             javascriptBundle.AddDirectory("~/Scripts", "bootstrap-*.js");