英文:
Gradle: Use central declaration of dependencies in "subprojects" block
问题
我按照Gradle的说明来定义依赖关系的中心点。我使用libs.version.toml
文件来实现这一点。请参见:链接
举例来说,假设我有这个libs.versions.toml
文件:
[versions]
mockito = "4.1.0"
[libraries]
mockito = { module = "org.mockito.kotlin:mockito-kotlin", version.ref = "mockito" }
现在,在根或子项目的build.gradle
中使用它是可以的,但在定义subprojects
块时,用于定义所有子模块的依赖项和插件时,它不起作用。以下是根build.gradle
的示例:
plugins {
(...)
}
// 仅为此模块添加依赖关系
dependencies {
testImplementation(libs.mockito) // 正常工作
}
subprojects {
// 为每个子模块添加依赖项
dependencies {
testImplementation(libs.mockito) // 不起作用
}
}
是否有一种方法可以实现这一点,而不必将每个依赖项添加到每个子项目的build.gradle
中?我使用的是Gradle 8.0.1。
英文:
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
得分: 2
这是Gradle中subproject
和allproject
块实现方式的一个后果。
你可以通过在libs
访问前加上rootProject
前缀来使其工作:
subprojects {
// 向每个子模块添加依赖
dependencies {
testImplementation(rootProject.libs.mockito) // 现在有效
}
}
你可以在Gradle问题跟踪器中找到更多相关信息。
然而,Gradle建议使用约定插件替代allproject
/ subproject
构造。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论