根目录中定义的闭包在子级中不可见 [英] Closure defined in root not visible in child
问题描述
我有根项目和子项目(:child
).
根构建看起来像这样:
I have root project and subproject (:child
).
Root build looks like like this:
def foo = {
println("foo")
}
allprojects {
task bar << {
println(project.name + ":bar")
}
afterEvaluate {
foo()
}
}
正在运行gradle bar
打印:
foo
foo
:bar
:child:bar
child:bar
parent:bar
这很有道理.但是,IRL我需要foo
由孩子的构建文件调用(因为我希望仅由某些子模块调用它).
文档似乎很清楚:In a multi-project build, sub-projects inherit the properties and methods of their parent project
This make sense. However, IRL I need foo
to be called by the child's build file (because I want it to be called only by some of the submodules).
The documentation seems to be clear enough: In a multi-project build, sub-projects inherit the properties and methods of their parent project
但是,将上面的"afterEvaluate"块移到child/build.gradle
中会导致错误:Could not find method foo() for arguments [] on project ':child' of type org.gradle.api.Project
.
However, moving the "afterEvaluate" block above into child/build.gradle
results in an error: Could not find method foo() for arguments [] on project ':child' of type org.gradle.api.Project
.
为什么会发生这种情况,我该如何解决?我尝试了很多不同的变化-将def
移动(到buildscript
,allprojects
,ext
,allprojects.ext
,使其在ext中成为变量,而不是方法等). ,以不同的方式引用它(例如rootProject.foo
,rootProject.foo()
,ext.foo()
等)-似乎没有任何效果.
Why does this happen and how do I fix this? I have tried a whole bunch of different variations - moving the def
around (to buildscript
, allprojects
, to ext
, to allprojects.ext
, making it a variable in ext, instead of a method etc.), referring to it differently (as rootProject.foo
, rootProject.foo()
, ext.foo()
etc.) - nothing seems to work.
有什么想法吗?
推荐答案
需要在ext名称空间中声明各种变量,以便将它们传播到下游.试试:
Vars need to be declared in the ext namespace for them to be propagated downstream. Try:
ext.foo = {
println("foo")
}
ref: https://docs.gradle .org/current/dsl/org.gradle.api.plugins.ExtraPropertiesExtension.html
这篇关于根目录中定义的闭包在子级中不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!