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?
Click on Environment variables. After that, click the New option. Now, create user variable, enter the variable name as Gradle_Home and paste the value of the home path e.g., C:\gradle-6.0. 1 in the variable value field.
Environment variables are needed to customise the execution of the gradle tasks. Below is the working code in gradle 7.3.
Here, we don't use properties to pass arguments. Instead, we pass the –args flag and the corresponding inputs there. This is a nice wrapper provided by the application plugin. However, this is only available from Gradle 4.9 onward.
The subproject producer defines a task named buildInfo that generates a properties file containing build information e.g. the project version. You can then map the task provider to its output file and Gradle will automatically establish a task dependency.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With