我想创建一些函数来读取源.coffee文件,使用CoffeeScript解析器检查AST(可能使用traverseChildren函数),更改一些节点,然后将更改后的AST写回目标.coffee文件。
这种操作的一个简单(但没用)的例子是,我想找到树中的所有字符串并连接“Luis就在这里”。所以,如果我有
console.log 'Hello, world!'
然后在我的函数完成文件之后,它将生成:
console.log 'Hello, world!Luis was here'
哪个仍然是CoffeeScript,而不是“已编译”的JavaScript。读取.coffee和生成.js非常容易,但这不是我想要的。我找不到使用CoffeeScript API进行此类任务的方法。
先谢谢你的帮助......
答案 0 :(得分:2)
由于CoffeeScript编译器是用CoffeeScript编写的,因此您可以在CoffeeScript中使用它。编写另一个CoffeeScript程序来读取源代码,操作AST然后编写JavaScript:
一个简短的例子,在mycustom.coffee文件中说:
fs = require 'fs'
coffee = require 'coffee-script'
generateCustom = (source, destination, callback) ->
nodes = coffee.nodes source
# You now have access to the AST through nodes
# Walk the AST, modify it...
# and then write the JavaScript via compile()
js = nodes.compile()
fs.writeFile destination, js, (err) ->
if err then throw err
callback 'Done'
destination = process.argv[3]
source = process.argv[2]
generateCustom source, destination, (report) -> console.log report
调用此程序,如:
> coffee mycustom.coffee source.coffee destination.js
也就是说,如果您的转换非常简单,那么您可以通过操作令牌流来更轻松地创建自定义重写器。