Search code examples
coffeescriptcakefile

compile and join coffeescript files


I have the following structure:

/lib
  / myfile.js.cofee
  / secondfile.js
/src

and i would like to compile them into

/lib
  / myfile.js.cofee
  / secondfile.js
/src
  / awesomefile.min.js

I have read about Cakefiles, but i'm not sure how to exactly do this.

Thanks, Mike


Solution

  • If you happen to be using something based on connect (e.g. express), I'd recommend using connect-assets. If not, then grunt may be a good bet, as was previously suggested. If you'd like to do this yourself using a Cakefile, here is one approach you could use:

    Note that the convention is to build from src to lib (which is the reverse of what you stated in the question). I'll use that convention below, but you can easily switch it back if needed.

    $ npm install snockets

    place the following in src/awesomefile.coffee:

    #= require secondfile.js
    #= require myfile.js.coffee
    

    create a Cakefile with the following:

    fs = require 'fs'
    Snockets = require 'snockets'
    
    NAME = 'awesomefile'
    INPUT_FILE = "src/#{NAME}.coffee"
    OUTPUT_FILE = "lib/#{NAME}.min.js"
    
    task 'build', 'Build lib/ from src/', ->
      snockets = new Snockets()
      js = snockets.getConcatenation INPUT_FILE, async: false, minify: true
      fs.writeFileSync OUTPUT_FILE, js
    
    task 'clean', "remove #{OUTPUT_FILE}", ->
      fs.unlinkSync OUTPUT_FILE
    

    Now you can just do:

    $ cake build

    and that will create a lib/awesomefile.min.js.

    You can have the files in src track their own dependencies, or you can list the order to be included in a single file like I've done above. For more, you can check out the snockets repository. Also note that the compiling chapter chapter of The Little Book on CoffeeScript is a good resource for learning about cake files.