Friday, 21 April 2017

Building less from ANT without funny plugins

There are a few libraries from non-trustworthy individual developers which do compile LESS style-sheets in java, most of them are not very transparent: some of them download node.js, some of them use rhino. It is possible to do it in clear, obvious way from your ant build, see the example for Windows below.

Properties to be defined:
${your.extensions.dir} - is some dir to put NodeJS to;
${your.web.sources.dir} - is a dir for static web files, to put CSS into.

This config downloads NodeJS, installs LESS locally and compiles styles.
This example is for windows. Linux or MacOS version is similar: just define right path in ${nodejs.exec.dir} and in `<get src=...`;  Replace `executable="cmd"`, `osfamily="Windows"` and `<arg value="/c"/>` as appropriate to your system. Node.JS can also be installed with system package manager, `_install_node` task is not needed in this case.

<property name="nodejs.dir" location="${your.extensions.dir}/nodejs"/>
<property name="nodejs.version" value="6.10.2"/>
<property name="nodejs.exec.dir" location="${nodejs.dir}/node-v${nodejs.version}-win-x86"/>
<property name="less.version" value="2.7.2"/>
<property name="less.dir" value="${your.web.sources.dir}/includes" />

<target name="_install_node">
    <if>
        <not><available file="${nodejs.exec.dir}"/></not>
        <then>
            <echo message="installing nodejs..."/>
            <mkdir dir="${nodejs.dir}"/>
            <get src="https://nodejs.org/dist/v${nodejs.version}/node-v${nodejs.version}-win-x86.zip"
                 dest="${nodejs.dir}"
                 usetimestamp="false"/>
            <unzip src="${nodejs.dir}/node-v${nodejs.version}-win-x86.zip" dest="${nodejs.dir}/"> </unzip>
        </then>
    </if>
</target>

<target name="_install_node_less" depends="_install_node">
    <if>
        <not><available file="${nodejs.exec.dir}/lessc.cmd"/></not>
        <then>
            <echo message="installing less for node from npm..."/>
            <exec dir="${nodejs.exec.dir}" executable="cmd" osfamily="Windows">
                <arg value="/c"/>
                <arg value="${nodejs.exec.dir}/npm.cmd"/>
                <arg value="install"/>
                <arg value="less@${less.version}"/>
            </exec>
        </then>
    </if>
</target>

<target name="generate-styles" depends="_install_node_less">
    <echo message="compiling less..."/>
    <exec dir="${nodejs.exec.dir}" executable="cmd" osfamily="Windows">
        <arg value="/c"/>
        <arg value="${nodejs.exec.dir}/lessc.cmd"/>
        <arg value="${less.dir}/styles.less"/>
        <arg value="${less.dir}/styles.css"/>
        <arg value="--source-map"/>
    </exec>
</target>