Search code examples
node.jscoffeescriptcakefile

How to compile coffeescript to the parent directory of the source?


I just got into the world of caffeine and I'm having a bit of trouble with Cakefiles.

It is my understanding that Cakefiles use the coffee script syntax; if I want to look for a file in child directories, I need to require the fs module and do whatever I need to do as if I'm in a nodejs app right? And I need only one Cakefile for the whole project, correct? Do I need to make any changes to package.json or anything to the project to use Cakefile?

That being said, as I was looking at some examples at this delicious cakefile tutorial I have come across this following snippet:

{exec} = require 'child_process'
task 'build', 'Build project from src/*.coffee to lib/*.js', ->
  exec 'coffee --compile --output lib/ src/', (err, stdout, stderr) ->
    throw err if err
    console.log stdout + stderr

I wanted to put my coffescripts under /coffee directory and I wanted them to compile to / for each coffee script it found. For example if it found routes/coffee/index.coffee the compiled js should be outputted as routes/index.js. In order to do that I tried running $ coffee --output ../ . but since it didn't work --although I thought it was worth the try-- I tried doing that with Cakefile.

{exec} = require 'child_process'
task 'build', 'Build project from *.coffee to ../*.js', ->
  exec 'coffee --compile --output ../ .', (err, stdout, stderr) ->
    throw err if err
    console.log stdout + stderr

Which is the altered version of the snippet above. It didn't work as well. I'm trying to learn more about cakefiles so that I can maybe write a function that rememberes the pwd and goes up one directory, sets output as that directory while it is compiling coffee scripts.

If you could lead me to a solution or a source that could help me find the solution I would appreciate it. However please keep in mind that I do not understand the advanced coffee-script stuff from the documentations... Examples with results would be more useful for my skills in development.


Solution

  • I think the key difference here is the working directory.

    - root
    -- lib
    --- foo.js <- target
    -- src
    --- foo.coffee
    

    When you have that setup, and from root, you run coffee --compile --output lib/ src/ it works because root/lib and root/src are both easily found from root.

    - root
    -- foo.js <- target
    -- coffee
    --- foo.coffee
    

    Now, from root when you run coffee --compile --output ../ ./ then you set the output directory to root/.. and the input directory to root/. (or simply root.)

    Which means, when you run this command from root you want simply:

    coffee --compile --output ./ coffee/
    

    Or if you cd coffee/, then this:

    cd coffee
    coffee --compile --output ../ ./
    

    Should work fine.