by Joakim

Bundling of CSS and JavaScript in MVC 4 Beta

MVC 4 Beta comes with support for bundling (and minification) of CSS and Javascript out of the box which is pretty neat.

By adding link- and script-tags like the ones below, you will you get the content from all the css- or js-files in the given directories minified and bundled together into a single resource, or will you?

<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/css")" rel="stylesheet" type="text/css" />
<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script>

I added a custom css-file to “~/Content/”, as well as a custom js-file to “~/Scripts/” and expected them to become part of the resource bundles automagically, however that was not the case at all! So what gives?

It turns out that the method “BundleTable.Bundles.RegisterTemplateBundles();”, which is called under “Application_Start” in “Global.asax.cs”, contains hardcoded values for which resources that should be added to the bundles (default files such as site.css, jquery.cs, etc).

However, if you replace “BundleTable.Bundles.RegisterTemplateBundles();” with “BundleTable.Bundles.EnableDefaultBundles();” things work like you would expect them to. The latter actually looks in the specified directory and finds all the css- and js-files which is them minified and bundled together. If you ask me, this should have been the default used in the “MVC 4 Web Application”-template.

Another way to have all the files included in your bundles is to create and add them to the bundle collection yourself like so:

protected void Application_Start()
{
    Bundle styles = new Bundle("~/MyStylesBundle", new CssMinify());
    styles.AddDirectory("~/PathToMyStyles", "*.css");
    BundleTable.Bundles.Add(styles);

    Bundle scripts = new Bundle("~/MyScriptBundle", new JsMinify());
    scripts.AddDirectory("~/PathToMyScripts", "*.js");
    BundleTable.Bundles.Add(scripts);
}

Note! Since MVC 4 is still in beta, this may change (hopefully it does)!

Comments