ASP.net
MVC 4 comes with new feature called bundling and minification.
var mainWebStyle = new Bundle("~/Scripts/libs", typeof(JsMinify));
mainWebStyle.AddFile("~/Scripts/jquery-1.7.1.min.js");
mainWebStyle.AddFile("~/Scripts/Knockout-2.0.0.js");
BundleTable.Bundles.Add(mainWebStyle);
In
the above example, we can how bundles are created. This this example, we are
bundling up two js file into one lib1 file. we can also bundle all the files in
one folder with the following code.
var mainWebStyle = new Bundle("~/Scripts/libs", typeof(JsMinify));
mainWebStyle.AddDirectory("~/Scripts",
"*.js", false);
BundleTable.Bundles.Add(mainWebStyle);
And
in the view we can refer to bundled file like this.
<script src="@Microsoft.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/libs")" type="text/javascript"></script>
Microsoft.Web.optimization
help to cache the file on the clients machine and at the same time also adds a
magical versioning number to the file which changes if file is changed, hence
forcing the client to request for new file if file is modified and not refer to
cached file on the client side.
We
can also use our own minification utility if we dont like the one provided by
the microsoft e.g
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.Optimization;
using Yahoo.Yui.Compressor;
namespace MVC4Example
{
public class YuiJsMinify : IBundleTransform
{
public void Process(BundleResponse bundle)
{
if (bundle == null)
{
throw new ArgumentNullException("bundle");
}
bundle.Content = JavaScriptCompressor.Compress(bundle.Content);
bundle.ContentType = "text/javascript";
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.Optimization;
using Yahoo.Yui.Compressor;
namespace MVC4Example
{
public class YuiCssMinify : IBundleTransform
{
public void Process(BundleResponse bundle)
{
if (bundle == null)
{
throw new ArgumentNullException("bundle");
}
bundle.Content = CssCompressor.Compress(bundle.Content);
bundle.ContentType = "text/css";
}
}
}
In
the above example, i have used Yahoo Yui compressor dll to minify my javascript
and style files instead of JsMinify and CssMinify.
Please visit the link of the presentation that Scott Gu gave in Netherlands to demo bundling and
minifications and some other new features coming out in MVC 4
Happy
Coding