Minification and Bundling in MVC3
I have been testing ASP.net MVC4 lately and one of the things I really like in it is the built in minification and bundling that it provides. I discovered the other day that there is a nuget package that contains this MVC4 bundling and minification. The problem I ran into with the nuget package is that it uses a different namespace than the actual file in MVC4. The nuget package uses Microsoft.Web.Optimization and MVC4 uses System.Web.Optimization so I was unable to get the nuget package to work properly in my view. Then I thought to myself “I already have the actual file in my MVC4 project”, so I grabbed it from my project and dropped it into the bin folder of my MVC3 project and added a reference to it. What do you know, it works!!
So here is how to use it:
- Reference the System.Web.Optimization dll file in your project. I suggest getting it from an MVC4 project or downloading it here.
- Open up your global.asax file and add this line to the end of your Application_Start() function.
1)BundleTable.Bundles.EnableDefaultBundles();
Add bundling to your view(s)
@using System.Web.Optimization
<link rel="stylesheet" type="text/css"
href="@BundleTable.Bundles.ResolveBundleUrl("~/stylesheets/css")" />
<script type="text/javascript"
src="@BundleTable.Bundles.ResolveBundleUrl("~/scripts/js")"></script>
The last part of the bundling path is the file type to bundle, so in my examples the paths are actually “/stylesheets” & “/scripts”. This takes all of the css files in the stylesheets folder and combines and minifies them into a single file. It does the same thing with the js files in the scripts folder.
The output will look similar to this:
<link rel="stylesheet" type="text/css" href="/stylesheets/css?v=oI5uNwN5NWmYrn8EXEybCIbINNBbTM_DnIdXDUL5RwE1" />
<script type="text/javascript" src="/scripts/js?v=cuu54Mg4FexvXMQmXibMetb08jdn7cTR1j-MSVxFRPE1"></script>
As you can see, it gives the bundled files a version id so that you can cache the files and when you make a change to one of them, the ID will change so that your browser will download the new changes.
Just as a warning, MVC4 is still in beta so be careful with using this file. The final version of the system.web.optimization will probably be different
No comments:
Post a Comment
If any doubt?then please comment in my post