2013-08-02 142 views
0

我想制作一些函数来读取源.coffee文件,使用CoffeeScript分析器检查AST(可能使用traverseChildren函数),更改一些节点,然后将更改后的AST写回目标.coffee文件。如何使用CoffeeScript API来操纵AST并编写.coffee输出

一个简单的(但是没用的)这种操作的例子是,我想找到树中的所有字符串并连接“Luis在这里”。所以,如果我有

console.log 'Hello, world!' 

然后我的功能通过文件消失后,它会产生:

console.log 'Hello, world!Luis was here' 

仍然是CoffeeScript的,而不是“编译”的JavaScript。阅读.coffee和生成.js文件非常容易,但这不是我想要的。我找不到使用CoffeeScript API执行此类任务的方法。

在此先感谢您的帮助...

回答

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

也就是说,如果您的转换非常简单,那么您可能更容易通过操作令牌流来创建自定义重写器。

+0

非常感谢,我会尝试一下。 –