How to automatically compile LESS into CSS on the server?

romaninsh picture romaninsh · Nov 28, 2012 · Viewed 9.7k times · Source

Friend designer of mine was compiling his LESS file manually and uploading it with Coda (Remote Site) spending lots of precious time. He asked me:

Is it possible to automatically detect file change on the Linux server and compile without delay at all?

Answer

romaninsh picture romaninsh · Nov 28, 2012

I have made a script and I publish the details:

  • Easy to use for designers
  • Executes LESS compiler immediately after file is saved, without consuming server resources
  • Any editor capable of remote editing will work with this solution - Code, Sublime Text, Textmate

First, you need to install "npm" on the server by typing this into the console:

sudo apt-get install npm inotify-tools
sudo npm install -g less
sudo nano /usr/local/bin/lesscwatch

Paste the following into the file:

#!/bin/bash
# Detect changes in .less file and automatically compile into .css
[ "$2" ] || { echo "Specify both .less and .css files"; exit 1; }
inotifywait . -m -e close_write | while read x op f; do.
    if [ "$f" == "$1" ]; then.
        lessc $f > $2 && echo "`date`: COMPILED";.
    fi
done

Save, exit, then execute:

sudo chmod +x /usr/local/bin/lesscwatch

You are all done. Next time you need to work with your LESS files, you will need to open terminal (Coda has a built-in), go to the folder of your file (using cd) and execute this:

lesscwatch main.less main.css

It will output information about successful compilations or errors. Enjoy.