MSBuild task to compile LESS files

When you are using LESS to create dynamic style sheets the performance of your website will increase when you compile those files to CSS before uploading the webapplication to a server. In this post I’ll describe how to create a build task for MSBuild that will compile all LESS files in a directory. I use this task in my deployment environment for web applications. It is part of a series of tasks that build the application, copies all the files to a deployment directory and does some post processing (compressing JavaScript, images, etc.). Of course it is possible to compile LESS files dynamically using a HttpHandler as well, for more information visit dotless.org.

Note: the following code compiles all LESS files in a specific directory to CSS, and removes the LESS files to prevent others seeing your code. Therefore do not run this task on your development directory.

First you have to download the LESS compiler for Windows/.NET here, and save it somewhere on your harddisk.

Now create a new class library project in Visual Studio, and create a new class named ‘LESSCompiler’. The code is as follows:

In your MSBuild file import the task:

Create a new target:

When the LESS compiler executable has a different name than default use this property: CompilerFileName=”compiler-filename-example.exe”. By default the task will remove all compiled LESS files, to turn this off use: DeleteOriginalFiles=”false”.

The Ignore property is used to ignore specific files. It might happen that some LESS files use functions that are defined in other files and therefore cannot be compiled independently, and as a result compiling fails.

This is all. The code in this post is not perfect, but it works for me. If you have some questions or suggestions please comment!

Leave a Reply

Your email address will not be published. Required fields are marked *