One of the cool new features of .Net 4.5 is the bundling and minification feature. This can save so many requests to your server and saves you many kbs without creating a debug hell. The amount of data is getting more and more important, because of the mobile devices. People pay lots of money on data bundles for their mobile device, we better not waste it. It also decreases loading time!! Reasons enough to start using bundling and minification!
First thing you need to do is download and install the Microsoft ASP.NET Web Optimization Framework nuget package.
The bundles are registered at application startup. This event is handled in the Application_Start method in the Global.asax. I always try to keep my Global.asax as clean as possible and split all registrations to seperate files in the App_Start folder. So I created a static BundleConfig class in the App_Start folder. This class contains one method, Register with the current Bundles as argument.
This creates a Stylesheet bundle names “~/content/css”” and contains one file “~/Content/site.css”. Adding more files is easy, just add more files to the include and separate them by a comma.
Adding bundles to a view
The only thing left to do, is adding the bundles to a view.
<%: Scripts.Render("~/bundles/jquery") %>
<%: Styles.Render("~/Content/css") %>
The above code renders the Stylesheet bundle.
All the requests to the bundles have a querystring parameter (v=CkVTG71m7lHB5jSCpyOSxbeCVJLIPag7u7NL4ykFenk1). This is to make sure that no old versions of this file are cached and retrieved.
Bundles can also be configured in config files. This allows you to make changes to your bundle without having to rebuild the project. It also allows frontend developers to easily include, remove or change files in a bundle without having to use visual studio.
An example of a bundle.config file
<?xml version="1.0" encoding="utf-8" ?>
<include path="~/Content/Site.css" />
One of the biggest problems of minified files is debugging. It’s almost impossible to debug those files.
That’s when the best feature of this minification framework comes in place. When compilation is set to debug (in web.config), the files will not be minified, which makes it a lot easier to debug.
<compilation debug="true" />
<!-- Lines removed for clarity. -->
Creating custom bundle transforms
Custom transforms can be created by implementing the IBundleTransform interface.,
public class MyByndleTransform : IBundleTransform
public void Process(BundleContext context, BundleResponse response)
// Process bundle tranform here
The custom transform can now be added to the transform of a bundle
var myBundle = new Bundle("~/My/Files/To/Include");
This bundle can now be added to the bundles collection in the BundleConfig file.
Why creating custom bundle transforms? Just think of less or coffeescript, or whatever bundle you want.