Writing a node module in CoffeeScript

I recently wrote a node module and used CoffeeScript instead of vanilla JavaScript to write it. The reason for this was that I didn’t feel like dealing with some of the silliness of JavaScript and I really like some of CoffeeScript syntaxic sugars.

1. Compile the files

The first step is to make sure your code is compiled into vanilla JavaScript before publishing. For this purpose, I used a Cakefile that contains a single rule:

task 'build', 'Build lib/ from src/', ->
  coffee = spawn 'coffee', ['-c', '-o', 'lib', 'src']

  coffee.stderr.on 'data', (data) ->
    process.stderr.write data.toString()
  coffee.stdout.on 'data', (data) ->
    print data.toString()

This rule will compile every .coffee file in the src folder into a JavaScript file and put it in the src folder.

2. Ignore the CoffeeScript files

Simply add the folder containing your CoffeeScript code, along with the other files unnecessary to the module, to the .npmignore file. In this case, we only need to add the src folder:

src/

3. Publish it on the npm registry

To publish on the npm registry, you need an account so npm is able to know who you are:

npm set init.author.name "Desmond Hume"
npm set init.author.email "desmond.hume@gmail.com"
npm set init.author.url "http://desmond.is"

Finally, assuming your module is finished and contains a package.json file, you can publish it using:

npm publish

Edit from May 29th:

3.bis Compile the files before publishing

I recently learned that you can have npm compile your files before publishing by adding a script in your package.json file.

"scripts": {
  "prepublish": "cake build"
}

This means that everytime you run npm publish, it will run cake build before and compile your CoffeeScript code before publishing.