Express.js LESS Compilation

Here is a quick tutorial on how to get Express.js to automatically compile LESS stylesheets.

  1. Add LESS as a dependency in your package.json file:

    {
        "name": "application-name",
        "version": "0.0.1",
        "private": true,
        "dependencies": {
        ...
            "less": ">= 1.3.1"
        }
    }
    
  2. Use npm to install your new dependency by executing this command in your project's directory:

    npm install
    
  3. Rename your stylesheets to have the extension .less instead of .css.

  4. Configure Express to use the LESS compiler:

    app.configure(function(){
    ...
        app.use(express.compiler({ src : __dirname + '/public', enable: ['less']}));
        app.use(app.router);
        app.use(express.static(__dirname + '/public'));
    });
    

Your stylesheets will now be compiled whenever you access a URL ending in .css and there is a matching filename with a .less extension. You will notice it saves static copies of the compiled stylesheets, but it's important to always edit the LESS file instead of the normal stylesheet so your changes don't get overwritten.

Posted on Nov 18, 2012
Written by Emlyn Murphy