ASP.NET 4.5 Bundling and Minification Update
Recently I wrote an article on the new bundling and minification features in ASP.NET 4.5. Out of the box, you get bundling and minifincation without really needing to do anything. If you missed it you can find it here.
Since that article, there have been some changes to ASP.NET 4.5. Previously you needed to manually add the following line of code in the Global.asax file:
protected void Application_Start()
{
BundleTable.Bundles.EnableDefaultBundles();
}
Since the update to ASP.NET 4.5, you no longer need to manually add that line of code. It’s automatically there when you begin a new project.
protected void Application_Start()
{
BundleTable.Bundles.RegisterTemplateBundles();
}
The code for referencing the bundled and minified CSS and JavaScript files has been updated too. Previously to reference a bundle, you’d add the following code:
<script src="scripts/js"></script>
<link href="content/css" rel="stylesheet" />
This is assuming you have your JavaScript files in a folder called scripts, and your style sheets are in a folder called content. This still works with this new release. The problem with referencing the files this way is when you update the files, the old versions will still be cached either by your browser, or by a web proxy. By default the files are cached for 1 year, this is great if you never update them! Microsoft has addressed this issue by allowing you to reference the bundled and minified files via ResolveBundleUrl.
<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script>
<link href="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content/css")" rel="stylesheet" type="text/css" />
The benefit of using ResolveBundleUrl is that it appends a magic string at the end of the file name. This magic string only changes when the file changes, meaning the files will be cached for 1 year or until they change. If you inspect the page through the developer tools in Google Chrome, you’ll see the magic string.
You can include a @using keyword to remove the need to fully qualify the System.Web.Optimization assembly.
@using System.Web.Optimization
Be certain to remember the use of this feature when developing with ASP.NET 4.5.