Pro-Tip: MVC Bundling Gotchas - Minimized Files and Stylesheet Order

16 July 2014

A few quick tips for anyone who's attempting to add scripts or stylesheets via bundling in ASP.NET MVC and wondering why things aren't working.

Minified Items

Say you have the following in your App_Start\BundleConfig.cs:

bundles.Add(new ScriptBundle("~/mybundle/sample").Include(
            "~/Content/Scripts/modernizr.custom.min.js",
            "~/Content/Scripts/site.src.js"
            ));

I've specified a path that isn't being handled by IIS (mybundle/sample is definitely not an actual location), and my site.src.js file is being added but not Modernizr. What gives?

Well, it turns out that the BundleCollection excludes *.min files by default (this applies to both Javascript and stylesheets). One way to get around this is to rename your files to exclude .min, but the approach I took was to tell the BundleCollection to stop excluding them:

//by default, .min files are excluded
bundles.IgnoreList.Clear();

bundles.Add(new ScriptBundle("~/mybundle/jssample").Include(
            "~/Content/Scripts/modernizr.custom.min.js",
            "~/Content/Scripts/site.src.js"
            ));

CSS Bundle Render Order

If your CSS stylesheets happen to require inclusion in a specific order, you'll probably need to know that the order of output css does not necessary follow the order specified in code. It looks like the default spits them out in alphabetical order, so if you had:

bundles.Add(new StyleBundle("~/mybundle/csssample").Include(
                 "~/Content/css/myadjustments.css",
                 "~/Content/css/core.css"
            ));

it'll actually appear on your page as this:

<link href="/Content/css/core.css" type="text/css" rel="stylesheet">
<link href="/Content/css/myadjustments.css" type="text/css" rel="stylesheet">

It appears that you can overwrite the ordering behaviour of the Bundler, but in my case I just decided to include them directly in my layout in the order I wanted.

So there you have it; two things to check when you're using the Bundler. Happy coding!

Tags: MVC, Bundling, Javascript, css

Add a Comment

No Comments