What is the best way to render LESS.js stylesheets in node.js using express?

Question!

I have a small node.js app (my first) that I want to have compile it's less.js stylesheets when the server loads. The point I'm starting at is the express example app for jade where it appears it compiles it's SASS templates when the server is created:

var pub = __dirname + '/public';

var app = express.createServer(
  express.compiler({ src: pub, enable: ['sass'] }),
  express.staticProvider(pub)
);

I saw this and hoped it would be as simple as changing sass to less but that doesn't appear to work.

Is there a different approach I should take? Is there something I'm missing? I can't find the documentation on the .compile method anywhere.

Thanks!



Answers

For express 3, use the following snippet:

var express = require('express'),
    less = require('less');

var app = express();
app.engine('less', function (path, options, callback) {
  fs.readFile(path, 'utf8', function (error, contents) {
    if (error) return callback(error);
    less.render(contents, options, callback);
  });
});


You have to compile less directly. Sass does not compile to less in express. It compiles directly to css. Same with less. It compiles directly to css.

var app = express.createServer(
  express.compiler({ src: pub, enable: ['less'] }),
  express.staticProvider(pub)
);


If you want to minify the outputted css, I found that the built in compiler (from the connect module) was missing the compress option. So rather than writing my own middleware compiler for it. I overwrote the connect less compiler in my app.

var express = require('express');
var app = express.createServer();
var less;

express.compiler.compilers.less.compile = function (str, fn) {
    if (!less) less = require("less");                                                      
    try {
        less.render(str, { compress : true }, fn);
    } catch (err) {
        fn(err);
    }
};

app.use(express.compiler({ src: publicdir, enable: ['less'] }));
By : Matt Sain


This video can help you solving your question :)
By: admin