C# .NET: Microsoft MVC: Setup CSS and JS Bundles and Minification in .NET MVC

12/17/2013 4:32:16 PM

Microsoft MVC now has support for CSS and JS bundling and minification. When used locally, the source files will be used. When used in production, minified versions of the files will be used. When multiple files are bundled together, they will be combined into 1 file and then minified. Any changes to the files on the server will force .NET to re-bundle and re-minify.

//1. If necessary, install the Microsoft.AspNet.Web.Optimization package from Nuget


//2. In App_Start folder
BundleConfig.cs file

using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;

namespace YourSite
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
			//jquery bundled with variables
            //bundles.Add(new ScriptBundle("~/bundles/scripts/jquery").Include(
            //			"~/Scripts/jquery-{version}.js",
            //			"~/Scripts/jquery.*",
            //			"~/Scripts/jquery-ui-{version}.js"));

			//jquery bundled with file individually selected
            bundles.Add(new ScriptBundle("~/bundles/scripts/jquery").Include(
                        "~/scripts/jquery-1.9.1.js",
                        "~/scripts/jquery-ui-1.10.3.js",
                        "~/scripts/jquery.validate.js",
                        "~/scripts/jquery.unobtrusive-ajax.js",
                        "~/scripts/jquery.validate.unobtrusive.js",
                        //"~/scripts/jquery.scrollTo-1.4.3.1-min.js",
                        "~/scripts/jquery.simplemodal.1.4.4.js"));           
						
			//css bundle
            bundles.Add(new StyleBundle("~/bundles/css/v1").Include(
                        "~/css/layout.css",
                        "~/css/screen.css",
						"~/scripts/jqueryui/redmond/jquery-ui-1.8.12.custom.css"));
        }
    }
}


//3. In Global.asax
protected virtual void Application_Start()
{
	...
	
	BundleConfig.RegisterBundles(BundleTable.Bundles);

	...
}


//4. In View files place CSS and JS - must use the same names as those declared above
@using System.Web.Optimization
<!-- css -->
@Styles.Render("~/bundles/css/v1")	
<!-- js -->
@Scripts.Render("~/bundles/scripts/jquery")