build.gradle中的代码。
node {
version = '8.17.0'
download = true
}
plugins{
id "com.moowork.node" version "1.3.1"
}
我在下面添加了获取已安装node版本的任务,并让npm任务依赖于该任务,在决定是否下载node时使用stdout值,但包含'download = true'的node块会在所有内容之前执行,并且每次都会尝试下载node。
task execute(type: Exec) {
commandLine 'node', '-v'
standardOutput = new ByteArrayOutputStream()
Set s = standardOutput.collect()
ext.stdout = {return s.getAt(0).toString()}
}
一个Gradle构建有 三段式:初始化、配置和执行。俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈俈 node { download = true }
会在配置阶段执行,而你的 execute
任务在执行阶段被执行。
为了在配置阶段计算结果,你应该改变你的 execute
任务到一个普通的Groovy函数。
bash-3.2$ cat build.gradle
ext {
nodeVersion = getNodeVersion()
}
def getNodeVersion() {
def baos = new ByteArrayOutputStream()
def execResult = project.exec {
commandLine 'node', '-v'
standardOutput = baos
}
return baos.toString();
}
task printNodeVersion {
doLast {
println(project.nodeVersion)
}
}
bash-3.2$ ./gradlew :printNodeVersion
> Task :printNodeVersion
v13.12.0
BUILD SUCCESSFUL in 566ms
1 actionable task: 1 executed
这里我将节点版本存储在扩展对象中。ext
在...期间 配置 时间,我将该值打印在 printNodeVersion
期间 执行 时间。
对于你的用例,你应该调用该函数,并检查返回值是否等于 "8.17.0"。配置 时间。如果是,则 node
二进制是8.17.0版本,否则,节点二进制是不同的版本(或者节点丢失)。