Sunday 13 July 2014

Adding bundling and minification to an empty MVC site

If you create an empty MVC application you’ll probably want to add features like bundling and minification. The process is very simple and starts with NuGet.

At the time of writing MVC is in version 5.

Get the NuGet optimization package

In Visual Studio Manage NuGet Packages…

image 

Search on the term ‘optimization’.

image

Install the Microsoft ASP.Net Web Optimization Framework. Notice that this has dependencies that will also be installed.

image 

Create your bundle configuration class

In the App_Start folder of your application create a new class called BundleConfig. Create a RegisterBundles(BundleCollection bundles) static method in the class which you will use to register your bundles. If you’re not familiar with bundles you’ll probably want to look-up ScriptBundle and StyleBundle from the System.Web.Optimization namespace to see how to do that.

Here’s an example that registers my CSS files:

namespace Mansio.Web.UI
{
    using System.Web.Optimization;

    /// <summary>
    /// This class handles bundle configuration.
    /// </summary>
    public class BundleConfig
    {
        /// <summary>
        /// Registers bundles with the application.
        /// </summary>
        /// <param name="bundles">The bundles to register.</param>
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/*.css"));
        } 
    }
}

Update Global.asax

The final step is to call the bundle configuration from Global.asax by calling your static RegisterBundles method from Application_Start.

/// <summary>
/// Called when the application starts.
/// </summary>
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

That’s all there is to it.

See also