How to Add/Modify CoffeeScript AST and write the result to a CoffeeScript file
minostro opened this issue · comments
Hey folks,
I would like to perform some changes in all the CoffeeScript files that are defined in a couple of repos that I have. I saw that by using coffeescript
I can get a hold of the AST by doing the following
coffeescript = require 'coffee-script'
ast = coffee.nodes("my-file.coffee")
The problem with this approach is that there is no way to write the modified AST back to a coffee file. I got a suggestion of compiling the AST(coffeescript) to javascript, and then use js2coffee
to write the result back to a coffeescript file. Is there a way to pass the modified AST(coffeescript) to js2coffee
to generate a coffeescript file?
You basically want to fork the compile
function from coffeescript.coffee
. In particular, this line:
fragments = parser.parse(tokens).compileToFragments options
can be rewritten as:
nodes = parser.parse tokens
fragments = nodes.compileToFragments options
In between these two lines, you can manipulate the nodes however you want.
EDIT: Just noticed you’re trying to get to CoffeeScript in the end. Sorry, not sure how to get there. The above will at least let you make your own version of the CoffeeScript compiler that includes your AST manipulations, then as you said you could pass that generated JS through js2coffee.
@GeoffreyBooth thanks for the insight!
@minostro Did you ever figure this out?
@GeoffreyBooth nope...unfortunately, got pull into something else :(