我有一个多项目的Gradle构建。在每个子项目中,我都有一个properties.gradle
文件,如下所示:
def usefulMethod() {
return 'foo'
}
ext {
foo = 'bar'
usefulMethod = this.&usefulMethod
}
然后使用
build.gradle
将其导入子项目apply from: './properties.gradle'
中。但是,如果两个子项目导入具有相同名称的变量,则会出现此错误:
Cannot add extension with name 'foo', as there is an extension already registered with that name.
似乎添加到
ext
会影响整个项目,而不仅仅是像我想要的子项目。从子项目中的外部文件导入属性和变量而不泄漏到整个项目构建中的正确方法是什么?
最佳答案
普通的ext
是ENTIRE项目,根项目和所有子项目的扩展。为了避免在通过apply from...
包含文件时污染根 namespace ,而应使用project.ext
。 project
是指当前正在构建的项目或子项目。例如,下面的文件可以是apply from
,以向当前项目添加downloadFile
函数:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'de.undercouch:gradle-download-task:3.4.3'
}
}
project.ext {
apply plugin: de.undercouch.gradle.tasks.download.DownloadTaskPlugin
downloadFile = { String url, File destination ->
if (destination.exists()) {
println "Skipping download because ${destination} already exists"
} else {
download {
src url
dest destination
}
}
}
}
关于gradle - 设置Gradle子项目的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51298317/