DotLess Bundling and Minification with ASP.NET MVC

Following the official ASP.NET tutorial I thought I had Less working nicely in my project with bundling but as soon as I started using CSS Imports I ran into the error “You are importing a file ending in .less that cannot be found.”…

You actually need to create a VirtualFileReader that implements IFileReader specifying the directory location of your .LESS files and you need to disable the DotLess caching & minifying features letting the standard ASP.NET bundling handle that for you.

Here’s what to do, first create your VirtualFileReader class:

internal sealed class VirtualFileReader : IFileReader
{
    public byte[] GetBinaryFileContents(string fileName)
    {
        fileName = GetFullPath(fileName);
        return File.ReadAllBytes(fileName);
    }

    public string GetFileContents(string fileName)
    {
        fileName = GetFullPath(fileName);
        return File.ReadAllText(fileName);
    }

    public bool DoesFileExist(string fileName)
    {
        fileName = GetFullPath(fileName);
        return File.Exists(fileName);
    }

    private static string GetFullPath(string path)
    {
        return HostingEnvironment.MapPath("~/Content/" + path);
    }

    public bool UseCacheDependencies
    {
        get { return false; }
    }
}

Then in your LessTransform class (if you don’t know what this is please follow the original tutorial link at the bottom of this post, it shows you how to bundle in ASP.NET MVC and how to use Less with DotLess)

public class LessTransform : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        DotlessConfiguration config = new DotlessConfiguration();
        config.MinifyOutput = false;
        config.ImportAllFilesAsLess = true;
        config.CacheEnabled = false;
        config.LessSource = typeof(VirtualFileReader);

        response.Content = dotless.Core.Less.Parse(response.Content, config);
        response.ContentType = "text/css";
    }
}

And my Less files were working again using imports, hope this is helpful.

The official ASP.NET tutorial: Bundling and Minification
The original blog post that got me on the right track: ASP.NET MVC Bundling of Bootstrap Less Source