LessCss and Rhino

Published on 18 July 2011


My colleague front designer is using less.js. It’s a tool to improve CSS with variables, mixins, and other goodness. I really like it because unlike SASS, the syntax stays close to CSS (and my old habits and editor don’t go crazy) but also because you can use it just by include it a Javascript file in your page. On the other hand, SASS requires Ruby so unless you’re already working with Rails, each developer needs to configure its environment for that and it’s a pain.

Get ready for production!

This is all good for development: you include your less stylesheet, your Javascript file and you’re good to go. But for production it’s kind of stupid to render the page on every user’s browser: it takes precious loading time. You’re better off generating the CSS file once from your Less file, and serve it compiled to your users. Less actually provides a way to do that, using Node.js. Indeed, LessCss being written in Javascript, it’s easy to understand why they chose Node.js.

But Node.js poses the same problem as SASS with Ruby: more work to setup a dev environment. I want anyone to be able to compile the files with a minimum of dependencies. This is why I turned my eyes to Mozilla’s Javascript implementation for the JDK, Rhino. If you can run less.js on Rhino, all you have to do is to ship rhino.jar with you code and anyone with a JDK can run it. Since all my projects today are in Play Framework, everyone involved has necessary a JDK installed. It’s particularly convenient to use Rhino because I’m already including it in my repositories for JsHint.

I have found a few posts about LessJS and Rhino, but they all involved either integration with some framework I don’t care, servlets, maven… Not what I wanted. I already have less.js included in the page for development mode, all I want is to be able to generate the CSS in command line or in an ant task. I’ve also found an ant task but that relies on the Node version of lesscss, so it kind of defeats the purpose.

Here comes my code

So here it is: rhino compatibility for LessCss. I did a pull request to ask for inclusion. The file you need is less-rhino-x.y.z.js.

You can use it in command line: java -jar rhino.jar style.less

Or in ant (make sure tool.rhino and tool.less point to rhino.jar and less-rhino.js):

<macrodef name="lessjs">
    <attribute name="input" />
    <attribute name="output" />
        <java jar="${tool.rhino}" fork="true" output="@{output}">
            <arg path="${tool.less}" />
            <arg path="@{input}" />
        <echo>Lessjs: generated @{output}</echo>

<target name="compilecss">
    <lessjs input="./public/stylesheets/main.less" output="./public/stylesheets/main.css" />

That’s all, folks! Now I have one more task to include to my pre-deployment task, along with JsHint checks and Closure Compiler minification…

TAGS: hacking