Skip to content

Instantly share code, notes, and snippets.

@itsjustcon
Last active May 1, 2021 06:28
Show Gist options
  • Save itsjustcon/5349218 to your computer and use it in GitHub Desktop.
Save itsjustcon/5349218 to your computer and use it in GitHub Desktop.
Uses Node.js to compile LESS files (on file change) into compressed css automatically! This simple script has saved me hours of compile & versioning mistakes by compiling everything automatically per-file! 1. Drop LESScompiler.js and struct.json into a folder with all your LESS files 2. Modify struct.json to fit your file names & output location…
var less = require('less'),
fs = require('fs'),
path = require('path'),
struct = path.join(__dirname,'struct.json'),
files = {};
// Watch current folder & compile if file from files{} has changed
fs.watch(__dirname,function (evt, file) {
file = path.relative(__dirname,file);
if ( !file || !files[file] ) return;
if (files[file]) compileLESS(file,files[file]);
});
// HELPERS
function compileLESS (from, to) {
from = path.join(__dirname,from);
to = path.join(__dirname,to);
fs.readFile(from,function (err, data) {
if (err) return;
less.render(data.toString(),{compress:true,paths:[__dirname]},function(e,css){
if (!e) fs.writeFile(to,css);
});
});
}
// Simply reads struct.json into files{}
updateFiles();
fs.watch(struct,updateFiles);
function updateFiles () {
fs.readFile(struct,function (err, data) {
if(err) return;
files = JSON.parse(data);
});
}
{
"file1.less" : "file1.css",
"file2.less" : "../www/file2.css",
"file3.less" : "../www/somefolder/more/file3.css"
}
@vanilla-thunder
Copy link

looks like less developers changed their render function to output an object instead of plain css.
I had to change rows 20 + 21 to get it working:

less.render(data.toString(),{compress:true,paths:[__dirname]},function(e,output){
    if (!e) fs.writeFile(to,output.css);

you can also see this in the official documentation:
http://lesscss.org/#using-less-configuration

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment