Using .less in ASP.NET MVC4

Update [2012-06-02]: Visual Studio 2012 RC includes a new bundle mechanism that supports chained transforms. Scott Hanselman posted an example that includes .less.

ASP.NET MVC 4 (beta) supports post-processed bundles which are especially useful for CSS style sheets and JavaScript. MVC 4 is shipped with minifiers for CSS and JavaScript, but you can also use your own post-processor. This is where you can plug in .less, using the dotlessClientOnly nuget package:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class LessMinify : IBundleTransform
{
    private readonly CssMinify _cssMinify = new CssMinify();
    public void Process(BundleContext context, BundleResponse response)
    {
        if (context == null)
            throw new ArgumentNullException("context");
        if (response == null)
            throw new ArgumentNullException("response");
        response.Content = dotless.Core.Less.Parse(response.Content);
        _cssMinify.Process(context, response);
    }
}

Now you can create bundles with your own minifier:

1
2
3
var styles = new Bundle("~/Content/myStyle", new LessMinify());
styles.AddFile("~/Content/someStyle.less");
BundleTable.Bundles.Add(styles);