Cake and cakefiles - actionanand/coffeescript-practice GitHub Wiki

Cake and cakefiles

Cake (annotated source and docs) is the companion task runner to CoffeeScript. It can be considered a "simplified" cousin of other, more complex task runners and build systems, such as Make and its descendants.

Cake can be run by executing cake in the command line, inside a directory that has a Cakefile. Tasks defined in the Cakefile can be run executing cake [task]. For example, if we like to compile every .coffee file in a directory (including subdirs), we can describe the taks like:

{ exec } = require 'child_process'

# compiles all .coffee files to .js files
task 'compile', 'compile all files in a directory', ->
  exec 'coffee --output dist -c src', (error, stdout) ->
    console.log error if error # Show errors if we run into any
    console.log 'Done.'

We can compile every .coffee file located in the "src" directory by running cake compile. Each compiled CoffeeScript file produces a .js equivalent in the "dist" directory.

Another popular approach is to join the compile file together in a single file, to save some time on http requests. This is also easily done with Cake and CoffeeScript:

{ exec } = require 'child_process'

# compiles all .coffee files and join them in a single .js file
task 'join', 'compile all files in a directory and join them', ->
  exec 'coffee --join dist/app.js -c src', (error, stdout) ->
    console.log error if error
    console.log 'Done.'

These should suffice for the course, since they cover the essential tasks we'll be using through it. However, if you'd like to get a bit fancier - why not give live compilation a try? :)

{ spawn } = require "child_process" # the fancier cousin of exec

# watches a directory for changes, and compiles .coffee files to a single file
task 'watch', 'live compilation', ->
  source = spawn 'coffee', ['-w','--join','dist/app.js','-c','src']

  source.stdout.on 'data', (out) ->
  	console.log out.toString().trim() # log to console on each compile to notify us of the change

  source.stdout.on 'error', (error) ->
    console.log error.toString().trim() # and notify us about any errors during compilation

While using these directly works, it's always a good idea to understand what they actually do. Since teaching node.js (which our Cake tasks use) is out of the scope of the course, please refer to the links in the resources section below for some further reading.

Resources