2012-03-28 123 views
8

我正在使用CoffeeScript(编写Cakefile)。我想编译一些其他的CoffeeScript文件,点菜CoffeeScript编译器API

coffee -o lib -c src 

我可以在一个子进程启动上面的命令,但是这种方法具有跨平台的问题,使错误处理困难。我宁愿使用API​​。

我很乐意使用command.coffee的确切功能,但我无法弄清楚。

附录:我看到require('coffee-script').compile,它将字符串编译为另一个字符串。这仍然会让我去做循环播放文件和子文件夹以及编写输出的繁琐工作。

+0

如果你也可以找到更丰富的API有用,请在Github上对功能请求发表评论https://github.com/jashkenas/coffee-script/issues/2386 – 2013-07-14 10:04:00

回答

11

您正在查找的API位于coffee-script.coffee。它导出一个compile函数,它能够完成它在锡上所描述的功能。

要直接使用command.coffee的run函数,您必须首先用您在命令行上传递的选项覆盖process.argv

+0

谢谢我试着重写'process.argv '但我没有把它关掉。你有一个例子吗? – 2012-03-28 22:09:06

+2

这适用于我:'command = require'coffee-script/lib/coffee-script/command','process.argv.push'-o','lib','-c','src'','' command.run()'。 – 2012-03-28 22:23:14

+0

返回值告诉我命令是否成功? – 2012-03-28 22:44:45

7

只需使用节点的fs API + coffeescript.compile

fs = require 'fs' 
coffee = require 'coffee-script' 

fs.readFile 'source.coffee', 'utf8', (err, data) -> 
    compiled = coffee.compile data 
    fs.writeFile 'source.js', compiled, (err) -> 
     console.log "Done." 

而且看一看的CoffeeScript自己Cakefile(使用子进程):https://github.com/jashkenas/coffee-script/blob/master/Cakefile

0

感谢约旦和莱纳斯我写道:

command = require('iced-coffee-script/lib/coffee-script/command') 
process.argv[2..]=['-o','lib','-c','src'] 
command.run() 

突出问题:run函数提前返回,并且没有回调来报告错误:\