Compile Less with Node, with dynamic variables

1.3k Views Asked by At

I'm building a SaaS project in NodeJS and I need to build CSS on the fly using LESS. I want to be able to change some of the less variables each time I build the css. The variables come from the database and can be different for each user (thus my pre-built static css files won't work).

So far I've found solutions for:

1) Reading the main.less file, which has imports, and it parses from there. No ability to change variables.

2) Reading all my less files into a string, appending my custom variable on the string and parsing it. For this I need to get all my less files into a string, which I can't do by pointing only to the main.less file. I need to create a file list which needs to be added to for every new file.

Is there a tool that allows me to do both? I want to point to my main.less file, add my custom variable, parse it and send the results to the browser.

1

There are 1 best solutions below

1
On BEST ANSWER

The 'less' package on npm will do this. You can simply pass in the custom variables in the options field. Although you have to watch out for path names in your less files, they must be absolute and not relative.

var input = fs.readFileSync(__dirname + '/../private/css/main.less', 'utf8');

var options = {
  modifyVars: {
    'var-name': '#000000'
  }
};


less.render(input, options, function (err, result) {
  // send response to end-user here
});