Android 构建变体:声明除一个变体之外的所有依赖项

Android build variants: declare dependencies for all but one variant

我有 5 个构建变体。 4 个不同的构建变体(“内部”)需要一组给定的 Gradle 依赖项和 1 个不需要的构建变体(“外部”)。引用这些依赖项的代码仅在内部构建变体的 /src 文件夹中。

我可以更简洁地声明“除此变体之外的所有变体”都需要给定的依赖项列表吗?

这就是我们现在的处理方式 app-level build.gradle file:

internalDevelopmentImplementation(name:'MyGreatDependency-1.1.0', ext:'jar')
internalDevelopmentImplementation(name:"MyGreatDependency-logger-1.1.0", ext:'aar')
internalDevelopmentImplementation(name:"MyGreatDependency-android-2.0.0", ext:'aar')
internalDevelopmentImplementation(name:"MyGreatDependency-extension-android-1.1", ext:'aar')

internalReleaseImplementation(name:'MyGreatDependency-1.1.0', ext:'jar')
internalReleaseImplementation(name:"MyGreatDependency-logger-1.1.0", ext:'aar')
internalReleaseImplementation(name:"MyGreatDependency-android-2.0.0", ext:'aar')
internalReleaseImplementation(name:"MyGreatDependency-extension-android-1.1", ext:'aar')

internalStageImplementation(name:'MyGreatDependency-1.1.0', ext:'jar')
internalStageImplementation(name:"MyGreatDependency-logger-1.1.0", ext:'aar')
internalStageImplementation(name:"MyGreatDependency-android-2.0.0", ext:'aar')
internalStageImplementation(name:"MyGreatDependency-extension-android-1.1", ext:'aar')

internalProdImplementation(name:'MyGreatDependency-1.1.0', ext:'jar')
internalProdImplementation(name:"MyGreatDependency-logger-1.1.0", ext:'aar')
internalProdImplementation(name:"MyGreatDependency-android-2.0.0", ext:'aar')
internalProdImplementation(name:"MyGreatDependency-extension-android-1.1", ext:'aar')

然后,externalProd 变体根本不声明依赖项。

有什么办法可以改善吗?

这里有一个想法:使用配置继承。创建一个具有大多数配置共享的依赖项的配置,在那里设置公共依赖项。让其他人从这个延伸。类似于:

configurations {
    // Add the bulk of dependencies to this one:
    commonImplementation {}

internalDevelopmentImplementation.extendsFrom(commonImplementation)
    internalReleaseImplementation.extendsFrom(commonImplementation)
    // And so on

免责声明:我还没有测试过这个。 检查 https://docs.gradle.org/current/javadoc/org/gradle/api/artifacts/ConfigurationContainer.html