Gradle + rhino 执行脚本

Gradle + rhino execute scripts

这是我第二次 gradle 使用,我对如何在 gradle 中执行 js 脚本有一点疑问。

我尝试使用 commandLine,它工作正常

task optimizeScript(type: Exec) {
    commandLine 'java', '-classpath', 'path/to/rhino/js.jar:path/to/closure/compiler.jar', 'org.mozilla.javascript.tools.shell.Main', 'r.js', 'main.js'
}

但我认为使用 gradle 有更好的方法。也许我可以在没有命令行的情况下执行脚本?我想首先我可以从 mvn 中获取这些依赖项,然后是编写脚本

dependencies {
  compile rhino
  compile otherstuff
}

task optimizeScript() {
  org.mozilla.javascript.tools.shell.Main('r.js main.js')
}

(当然这个脚本不行)

可以通过以下方式完成:

build.gradle

apply plugin: 'java'

repositories {
   mavenCentral()
}

dependencies {
   compile 'rhino:js:1.7R2'   
}

task runJS(type: JavaExec) {
   classpath configurations.compile
   main 'org.mozilla.javascript.tools.shell.Main'
   args 'run.js'
   standardOutput = new FileOutputStream(project.file('stdout'))
   errorOutput = new FileOutputStream(project.file('stderr'))
}

run.js

function f(x) {
 return x+1
} 
print(f(7))

在 运行 gradle runJS 之后,stdout 文件包含 8.