在子任务中定义的父任务中使用变量 [英] gradle use variables in parent task that are defined in child

查看:404
本文介绍了在子任务中定义的父任务中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多项目gradle构建,我在父构建中声明了一个使用在子项目中声明的变量的任务(该值可以根据子项目进行更改)。但是,在配置阶段出现错误,该变量不存在。我的设置看起来像

build.gradle(顶层)

 子项目{
myTask {
prop = valueDefinedInChild
}

}

然后

build.gradle(子项目)

  valueDefinedInChild ='someValue'

有没有办法正确地做到这一点? project.evaluationDependsOnChildren())有一种方法可以做到这一点(> project.evaluationDependsOnChildren()) ,但我建议只使用它作为最后的手段。相反,我会配置顶层的共同点,以及子项目级别的区别:

build.gradle(顶层):

 子项目{
任务myTask {//将任务添加到所有子项目
//常见配置转到此处
}
}

build.gradle(子项目):

  myTask {
prop ='someValue'
}

另一种避免重复的方法是将通用代码分解为单独的脚本,并让子项目通过 apply from:包含它。如果逻辑仅适用于选定的子项目,或者希望避免父项目和子项目之间的耦合(例如,使用Gradle的新配置按需功能)。


I have a multiproject gradle build where I declare a task in the parent build that uses a variable that gets declared in the child projects (the value can change depending on the subproject). However, I get an error during the configuration phase that the variable doesn't exist. My setup looks like

build.gradle (top level)

subprojects {
   myTask {
     prop = valueDefinedInChild
   }

}

And then

build.gradle (subproject)

valueDefinedInChild = 'someValue'

Is there a way to do this correctly?

解决方案

There is a way to do this (project.evaluationDependsOnChildren()), but I recommend to only use it as a last resort. Instead, I'd configure the commonalities at the top level, and the differences at the subproject level:

build.gradle (top level):

subprojects {
    task myTask { // add task to all subprojects
        // common configuration goes here
    }
}

build.gradle (subproject):

myTask {
    prop = 'someValue'
}

Another way to avoid repeating yourself is to factor out common code into a separate script, and have subprojects include it with apply from:. This is a good choice when the logic only applies to selected subprojects, or in cases where it's desirable to avoid coupling between parent project and subprojects (e.g. when using Gradle's new configuration on demand feature).

这篇关于在子任务中定义的父任务中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆