CoffeeScript - what I've should have done

· March 5, 2015

The blog post I wrote yesterday was from my experience at the time. I even ended the post with a call out for better ways.

And sure enough, twitter to the rescue:

As a side, this why I hang out on twitter. There are brilliant people there that will push you towards ever better. Thanks Erwin for this.

So… what does that mean for my post yesterday… Let’s find out:

First of all - nothing I wrote will cause you problems but it’s a bit cumbersome and maybe not the CoffeeScript-way… I think.

What worked

All the things I wrote under the “Initialize project and more” and “Run tests” headings is a ok way to get up and running with CoffeeScript on Node.

Doing that again means that you now have (see the other post for details):

  • Created a CoffeDemoTheCoffeeWay directory
  • git init in that directory
  • npm init in that directory
  • npm install mocha should --save-dev
  • created a test directory and a in that directory, with a simple test in it
  • added this test command in your package.json scripts/test-node: mocha --compilers coffee:coffee-script/register -R spec -u bdd -w
  • run npm test and seen your test pass

What could have been better

The part on writing and running .coffee-files could vastly be simplified by simply running the coffee directly.

Create a file in the root (touch and add the following code:

module.exports.greeting = greeting = (name) ->
	"Hello #{name}!"

console.log greeting "Marcus"

Now you can start this application directly by simply invoking coffee Doing that will result in printing the greeting:

Hello Marcus!

Our start command in the package.json can also be simplified a lot in other words:

"scripts": {
    "test": "mocha",
    "start" : "coffee"

Testing our system

Now we can continue as I wrote to test our system under test like this:

sut = require '../'
should = require 'should'

describe 'Writing Node with CoffeeScript', ->
	it 'is easy to get started testing... or is it?', -> true
	it 'can access exported functions in other modules', ->
		sut.greeting('Marcus').should.equal 'Hello Marcus!'

More improvements

So, that’s cool, but maybe we need to distribute a JavaScript version of the code as well. Now we are really into what should be put into a build system like grunt, gulp or even make, but for the sake of brevity let’s just create another npm script-node. In it we can now reuse the compile command from the previous post.

Here’s how the all my scripts look in the package.json-file.

"scripts": {
    "test": "mocha",
    "start" : "coffee index.CoffeDemoTheCoffeeWay",
    "build" : "coffee --compile --output dist ."

This will compile all the .coffee files in the root (and sub directories) and put them in the dist folder.


See… I told you in the header of this blog:

Sharing is learning

By sharing something I learned a better way. Thanks again Erwin!

Twitter, Facebook