MVC4 to MVC3 #1: Bundling and Minification
So here is how to do it:
First you need to get the required library files that were added to MVC4, which are System.Web.Optimization.dll and WebGrease.dll. If you aren't sure where you might find them, start a new MVC4 solution and copy the files from the generated bin folder to the MVC3 project's own bin folder.
Next, create a folder named App_Start and inside it create a new class named BundleConfig.cs. The skeleton for this new class is as follows:
public static void RegisterBundles(BundleCollection bundles)
Inside the RegisterBundles method, we will then add the necessary bundle information.
Now these bundles need to be initialised every time that the application is started. To do this, open the Global.asax.cs file and add this line somewhere in the Application_Start() method:
The last thing to do is to add a link for the virtual bundle inside the page. Easy, just add this line of code:
‹link rel="stylesheet" type="text/css" href= "@BundleTable.Bundles.ResolveBundleUrl("~/Content/css")" /›
Note that the name inside the parameter that we are passing (shown in bold) is the same as the one we added earlier, which is what makes the link work. Hurrah, we have a working bundling and minification solution on MVC3. The neat thing is that the generated file will also instruct the browser to cache it for one year, resulting in additional speed gains for repeated visits!