Skip to content

Instantly share code, notes, and snippets.

@StanAngeloff
Created June 6, 2012 14:05
Show Gist options
  • Save StanAngeloff/2882059 to your computer and use it in GitHub Desktop.
Save StanAngeloff/2882059 to your computer and use it in GitHub Desktop.
CoffeeScript `include ..` extension
fs = require 'fs'
path = require 'path'
CoffeeScript = require 'coffee-script'
CoffeeScript.on 'compile', (task) ->
task.input = task.input.replace /^([ \t]*)#=\s*include\s+(.*)$/im, (group, indent, file) ->
"#{indent}`#{ fs.readFileSync(path.join(path.dirname(task.file), file), 'utf8') }`"
@StanAngeloff
Copy link
Author

Hey! It was more of a quick way to pull in external JavaScript files at a pre-determined location for a little tool I am working on. Your code poses an interesting case, but given the limited scope, the way CS handles extensions and the explicit syntax I am OK with the current behaviour.

@michaelficarra
Copy link

Yeah, it should be fine for most practical cases. Still, my preferred way to do it would be to write regular function calls as statements (include "someFileName"), parse the file, replace those subtrees with the parse tree of the referenced file, and compile that instead.

@StanAngeloff
Copy link
Author

I actually do keep around a very old branch that did imports in a similar way (extended the grammar). I agree, AST manipulation is a more practical and bullet-proof approach, but at this compiler stage I'd need to re-parse the source twice (once in the extension and once in CS itself) and the LoC would likely explode.

Looking forward to anything you could offer in CS2 in terms of extensibility, been keeping up with the Wiki and Twitter.

EDIT: OK, maybe not explode, but definitely grow somewhat. I guess a parse -> AST -> walk -> substitute -> return JS chain would be enough.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment