ASP|NET MVC 4 Bundling And Minification
Thursday, 23rd February 2012
If you don't know why you would use this, here is a quick explanation of these two concepts.
So we are all agreed that bundling and minification rock. The problem is, nobody wants to maintain bundled and minified files - we want to work in neatly cohesive blocks that are laid out in a readable fashion. So we are also all agreed that bundling and minification should be automated at some later time than the development stage.
Enter ASP.NET MVC 4, which will do it all on the fly, will deal with caching and will make your pages a bit faster.
So how do we get our CSS bundled and minified. Well, in MVC 3 you have this:
<link href="styles/style1.css" rel="stylesheet"> <link href="styles/style2.css" rel="stylesheet"> <link href="styles/style3.css" rel="stylesheet">
And all we have to do in MVC 4 to get it all packaged up is this:
<link href="styles/css" rel="stylesheet">
<script src="scripts/jquery/jquery.min.js"></script> <script src="scripts/jquery/jquery.uppydowner.js"></script> <script src="scripts/script1.js"></script> <script src="scripts/script2.js"></script> <script src="scripts/script3.js"></script>
And now the MVC 4 equivalent...
<script src="scripts/jquery/js"></script> <script src="scripts/js"></script>
There is an HTML helper coming (Html.Bundle(...)) that will not only do all this, but also add a hash to the src attribute, which will change whenever the contents changes - so no more asking users to "force refresh" the page or clear their cache.
And finally, if you are having trouble trying out bundling, you may need to add this to your Application_Start() method: