A Better Solution for Less.css ...using vim, of course

Recently I’ve discovered the joys of working with less.css (not to be confused with the less framework, which is also related to CSS). I think the one thing that turned me on to the idea was the Less.app GUI application for Mac OS X.

Less.app monitors a directory and when there are any file changes to any .less files, it compiles a .css, minifies it, and places it in a /css directory, preserving a directory structure like the following:

site/
├── css
│   └── main.css
└── less
    └── main.less

I kind of liked this idea because I thought it kept everything neat. The only problem I had with Less.app is that it didn’t seem to work very often. I had a lot of issues where I would save a file and it would not pick the changes up. I had to hit save twice for it to pick up the changes, and even then sometimes it would crash completely and have to be restarted. It got to the point where I would have to restart Less.app 2–5 times in a one hour session. I am assuming that it was related to the way vim saves files, otherwise nobody else would be using this app. After 3 or 4 program updates I noticed the problem was still there and something had to be done.

I found out from a buddy that another tool called lessc was available from the creators of less. I had seen it mentioned in blog posts but I was never able to find it until one day I realized it was on their github page in the bin directory.

Grab lessc and make sure it’s in your $PATH. In order to use lessc, you need to install node.js. On OS X, this can be done via homebrew:

brew install node

or macports:

port install node

Or on Ubuntu using the following:

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

I created this bash script which wraps lessc to add some functionality:

lesscomp

    #!/bin/bash

    #compile less.css files, and compress them hardcore.
    if [[ $# == 1 ]]; then
        infile=$1
        outfile=$(basename ${infile%.*})
        outpath="$(dirname $infile)/../css"

        if [[ -d $outpath ]]; then
            outfile="$outpath/$outfile.css"
        else
            outfile="$(dirname $infile)/$outfile.css"
        fi
        lessc -x $infile |perl -ne 'chomp; print "$_";' > $outfile
    fi

The script attempts to save the output file to a css/ directory one level up from the .less file, assuming that directory exists. If it cannot find a ../css/ then it will output to the same directory as the input file. Place it somewhere in your path, I usually throw all of my scripts into $HOME/bin and add that to $PATH.

Then, add the following to your ~/.vimrc:

au BufWritePost *.less silent !lesscomp %
blog comments powered by Disqus