Gradle: Use central declaration of dependencies in "subprojects" block

429 views Asked by At

I followed Gradle's instructions to a central point to define dependencies. I am using the libs.version.toml file to do that. see: Link

For this example, let's assume, that i have this libs.versions.toml:

[versions]
mockito = "4.1.0"
[libraries]
mockito = { module = "org.mockito.kotlin:mockito-kotlin", version.ref = "mockito" }

Now using it in the root or subprojects' build.gradle works fine, but when defining the subprojects block, where I define dependencies and plugins for all submodules, it does not work. Example root build.gradle:

plugins {
    (...)
}

// add dependencies for this module only
dependencies {
    testImplementation(libs.mockito) // works
}

subprojects {
    // add dependencies to every submodule
    dependencies {
        testImplementation(libs.mockito) // doesn't work
    }
}

Is there a way to achieve this, without adding every dependency to each subprojects' build.gradle? I am using Gradle 8.0.1.

1

There are 1 answers

1
Louis Jacomet On BEST ANSWER

This is a consequence of the way the subproject and allproject blocks are implemented in Gradle.

You can make it work by prefixing the libs access with rootProject:

subprojects {
    // add dependencies to every submodule
    dependencies {
        testImplementation(rootProject.libs.mockito) // Now works
    }
}

You can find more information about this in the Gradle issue tracker.

However, Grade recommends to replace usage of allproject / subproject constructs with convention plugins.