Synchronous compilation in NodeJS

I am trying to write a script conversion for Browserify that allows me to require() .less files. The conversion will compile them into CSS and then wrap this miniature CSS into a small Javascript function that will add CSS to the page.

My problem is node-underscorify )

 var less = require('less'); var cleanCSS = require('clean-css'); var through = require('through'); module.exports = function(file) { if (!/\.css|\.less/.test(file)) { return through(); } var buffer = ""; return through(function(chunk) { return buffer += chunk.toString(); }, function() { compiled = buffer; if (/\.less/.test(file)) { compiled = less.render(compiled, function(e, r) { return r; }); } // rv comments compiled = compiled.replace(/\/\*.*?\*\//g, ""); // minify. TO DO: Get less.js to do this for us var compiled = cleanCSS.process(buffer); compiled = "(function($) { $('head').append('<style type=\"text/css\">" + compiled.replace(/'/g, "\\'") + "</style>');}(window.jQuery));"; this.queue(compiled); return this.queue(null); }); }; 

This works fine for a .css file, but splits into .less files since compiled is undefined.

There are several completed pull requests the less .js related to this, but no one works for me.

I am not very familiar with the through library, so maybe its behavior can be easily configured for asynchronous functions? I understand that for less.render() it makes sense to process @import asynchronously by default and do not mind rejecting imports in order to be able to directly require() LESS on my pages.

+6
source share
1 answer

It really works if you change it slightly. I was stupid with cleanCSS on buffer , not compiled

 var less = require('less'); var cleanCSS = require('clean-css'); var through = require('through'); var parser = new(less.Parser)({ processImports: false }); module.exports = function(file) { if (!/\.css|\.less/.test(file)) { return through(); } var buffer = ""; return through(function(chunk) { return buffer += chunk.toString(); }, function() { var compiled; // CSS is LESS so no need to check extension parser.parse(buffer, function(e, r) { compiled = r.toCSS(); }); // rv comments compiled = compiled.replace(/\/\*.*?\*\//g, ""); var compiled = cleanCSS.process(compiled); compiled = "(function($) { $('head').append('<style type=\"text/css\">" + compiled.replace(/'/g, "\\'") + "</style>');}(window.jQuery));"; this.queue(compiled); return this.queue(null); }); }; 
+1
source

Source: https://habr.com/ru/post/958001/


All Articles