gradle - 设置Gradle子项目的属性

标签 gradle build build.gradle

我有一个多项目的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.extproject是指当前正在构建的项目或子项目。例如,下面的文件可以是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/

相关文章:

java - ProcessException : ExecException: Process 'command ' /Library/Java/JavaVirtualMachines/jdk1. 8.0_31.jdk/Content/Home/bin/java

gradle - 如何使用环境名称设置Gradle测试命令

visual-studio - 确定它是在 Visual Studio 中的预链接步骤中调用的 .cmd 脚本中的构建还是重建

Gradle kotlin dsl - 如何指定重复任务?

android - Android Studio 4.1 更新后应用程序的 Gradle 构建错误

Android 收到 Retrofit 和 Retrofit 适配器的 DuplicateFileException 错误

visual-studio - Visual Studio 在构建期间不断挂起

build - 使用 easybuild cd 到目录

android - Gradle脚本-在file.delete()之前完成等待操作

android-studio - 找不到方法 buildTypes()