Stephen Newey

Keep Compiling CoffeeScript in OS X

07 April 2012

Lately I’ve been producing a lot of code in JavaScript. I use the word produce, because I’ve actually been writing the code in CoffeeScript. It better suites my Python sensibilities and is usually half the size of the resultant JavaScript.

The CoffeeScript compiler has a handy feature where it can watch a directory for you and any new or modified files are instantly compiled into JavaScript. By default these land next to their CoffeeScript originals, or optionally in a separate location.

CoffeeScript is brilliant, but using it has also resulted in wasted time trying to debug new code. I wondered why it didn’t seem to be doing anything only to realise I hadn’t started the compiler this session. None of my lovely new code was making it to the browser.

There must be a better way, and there is. It is one that resolves my OCD discomfort at having to leave a terminal running hosting the compiler, and that way is LaunchAgents.

LaunchAgents are OS X’s init.d, cron and such all rolled into a series of property list files that can be system wide or per-user. Creating one for CoffeeScript is dead simple.

I’m making some assumptions here that you’ve installed Node.js from Homebrew. If you’re not using Homebrew then you probably should be. I’m assuming you’ve then also installed CoffeeScript using npm and that you’ve not changed any of the default paths. If you have then you’ll want to adjust the recipe to suit.

All that’s required is a file like this stored in ~/Library/LaunchAgents and named appropriately.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "">
<plist version="1.0">

RunAtLoad makes sure the compiler launches whenever you log in. KeepAlive restarts the compiler in case it bums out for any reason.

To start it manually now, you can use the launchctl command.

launchctl load ~/Library/LaunchAgents/

If you want to stop it for any reason, replace load with unload.

You can check for any errors using All the usual compiler output will be directed to your system log.

The agent is simple to adapt to any watchful compiler, just change the strings inside the ProgramArguments array accordingly. I also use it for Compass.

Tags: coffeescript, osx, launchagents