emQonnect

MEN | MIND | METHODS

ASP.NET 4.5 Bundling and Minification

ASP.NET 4.5 is part of the newly announced .NET 4.5 Developer Preview. This release includes a lot of great core features in the ASP.NET runtime as well as ASP.NET Web Pages enhancements. One of the enhancement is Bundling and Minification.

Bundling lets you combine individual JavaScript and CSS files into a bundle that can be treated like a single file.
Minification condenses JavaScript and CSS files by removing whitespace and other characters that are not required. These features work with Web Forms, ASP.NET MVC, and Web Pages.

The bundling feature hooks into the ASP.NET routing mechanism and makes it possible to reference an entire folder instead of individual files. Suppose you have the following file structure.

You might want to bundle all .js files in the Scripts folder. To do that, you can now reference the folder and append /js to the path, as in this example:

You can do the same to bundle all the .css files in the Styles folder, but instead you append /css to the path:

When files are bundled, they are first sorted alphabetically (the way they are displayed in Solution Explorer). They are then organized so that known libraries and their custom extensions (such as jQuery, MooTools and Dojo) are loaded first. For example, the final order for the bundling of the Scripts folder as shown above will be:

  1. jquery-1.6.2.js
  2. jquery-ui.js
  3. jquery.tools.js
  4. a.js

CSS files are also sorted alphabetically and then reorganized so that reset.css and normalize.css come before any other file. The finalĀ  sorting of the bundling of the Styles folder as shown above will be as follows:

  1. reset.css
  2. content.css
  3. forms.css
  4. globals.css
  5. menu.css
  6. styles.css

The sorting algorithm is customizable.

You can register your own bundles in the Global.asax file in order to specify which files go into each bundle and what the exact URL will be. The following code shows how:

 

The custom bundle can now be referenced as in this example:

You can even override the default CSS and JavaScript bundles in order to call custom post-processing routines for the bundled files. In the following example, the built-in minification transforms are replaced with custom MyJsTransform and MyCssTransform types. The
types derive from the CSS and JavaScript minifier routines, respectively, and add custom functionality.

The bundling and minification feature is built with extensibility in mind, and
every part of the process can be extended or replaced,

Tagged as: ,