Search code examples
node.jslessextendmiddlewareuser-defined

How do I add functions to LESS in node.js


I used to use less-middleware, but switched to less as I needed to add custom functions/constants. I assume less-middleware uses less behind the scenes.

To define constants I used:

function lessDefine(name, value) {
  less.tree.functions[name] = function () {
    return new (less.tree.Anonymous)(value);
  };
}

and to create a constant:

lessDefine('backgroundImage', config.backgroundImage);

Then to link into Express:

router.use('/stylesheets',
  less.middleware(
    lessOpts.source, lessOpts.main,
    lessOpts.parser, lessOpts.compiler));

This was after crawling through bug reports, feature requests and google results, as the ability to extend LESS is not well documented. This worked last week, but now I see:

TypeError: Object #<Object> has no method 'middleware'

when I try to launch my node app.

What is the "correct" way to add functions/constants to LESS in Node.js?

Note that I use:

var less = require('less');
var lessMiddleware = require('less-middleware');

And my package.json uses the following version limits:

less-middleware: 1.0.3
less: 1.7.x

Solution

  • less.middleware is added by the less-middleware module.

    Monkeypatching is frowned upon for a reason; less-middleware had its own less module installed within its folder (by npm), while my app was using a separate instance of less.

    Hence, less.middleware was not being set in the instance of less that my app sees. After calling npm dedupe, the duplicate instances were consolidated and my app now works.