Billy Moon Billy Moon - 3 months ago 32
Less Question

Parse LESS client side

Can I parse LESS client side, and return the results?

I am currently using as recommended in documentation, which is to include less file, and minified less parser afterwards. I want to be able to return the raw css so I can save it as a css file.

I do not want to install node.js and the likes, I want a client side solution.

Answer Source

A look at the less.js source brings up the Parser object. Assuming that less.js is included in the page:

var data = "@colour: red; #example { background-color: @colour; }",
    parser = new less.Parser({});

parser.parse(data, function (error, root) { 
    // code that handles the parsed data here...
    // e.g.:
    console.log( root.toCSS() ); 

will output the following to the console:

#example {
  background-color: #ff0000;

The constructor for less.Parser actually takes series of settings, and I don't understand enough of the internals of LESS to say what might be good to pass (though they are all optional so passing none should just use the defaults).

The Parser.parse method takes two parameters: a string containing the LESS file, and a callback that handles the parsed data. The callback receives up to two parameters, an error object (error) and an object representing the parsed LESS (root). root isn't passed if there was a fatal error, and error will be null if there was no error.

Unfortunately, I can't find any better documentation on the attributes of the error parameter than the place they are set in the source here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download