Skip to content

版本目录 (Version Catalog)

源:使用版本目录管理依赖项

在以前,我们在各个模块的 build.gradle 中硬编码版本号,这会导致版本冲突和维护困难。Version Catalog 提供了一个中心化的位置 (libs.versions.toml) 来管理所有版本。

1. 优势

  • 类型安全: 拼写错误会在 IDE 中直接标红。
  • 集中管理: 一个文件控制全项目版本。
  • 依赖组: 支持将多个相关的库打包成一个 bundle(如:Compose 库组)。

2. 编写 toml 文件

位置:gradle/libs.versions.toml

toml
[versions]
# 定义版本号
ktx = "1.12.0"
compose = "2024.02.00"
retrofit = "2.9.0"

[libraries]
# 定义库引用
androidx-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "ktx" }
retrofit-core = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
retrofit-gson = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "retrofit" }

[bundles]
# 打包依赖组
network = ["retrofit-core", "retrofit-gson"]

[plugins]
# 管理插件
android-application = { id = "com.android.application", version = "8.2.2" }

3. 在构建脚本中使用

kotlin
dependencies {
    // 自动映射:androidx-ktx -> libs.androidx.ktx
    implementation(libs.androidx.ktx)
}
kotlin
dependencies {
    // 一次性引入 Retrofit 的多个库
    implementation(libs.bundles.network)
}
kotlin
plugins {
    alias(libs.plugins.android.application)
}

4. 依赖配置区别

配置名称描述适用场景
implementation依赖只对当前模块可见。推荐(最常用)。能加快编译速度。
api依赖会传递给依赖该模块的其他模块。基础核心模块(如::core:ui)。
compileOnly只参与编译,不打入包中。库开发、第三方 SDK。
kapt / ksp注解处理器。Room, Hilt, Glide。
testImplementation只在单元测试生效。JUnit, Mockito。