Gradle Version Catalog: A Step-by-Step Guide — Part 2
In the Part 1 of this series, we have discussed about the theory behind Gradle Version Catalog and its role in the dependency management. If you haven’t read it yet, I recommend to read it from here, for comprehensive understanding of this powerful tool.
Here the step-by-step guide on on how to create and implement a Gradle version catalog:
Before creating the file, make sure that you use Gradle 7.4 or newer
Create the version catalog file
The version catalog file can be in either TOML or JSON format. In your root project’s gradle
folder, create a file called libs.versions.toml
(By default, Gradle looks for the catalog in thelibs.versions.toml
so it’s better to use default name)
Here is an example of a version catalog file in TOML format:
# This is a version catalog file
[versions]
androidGradlePlugin = "7.0.4"
kotlin = "1.6.0"
androidx.core = "1.7.0"
androidx.appcompat = "1.4.1"
[library]
kotlin-stdlib = {
group = "org.jetbrains.kotlin",
name = "kotlin-stdlib-jdk8",
version.ref = "kotlin"
}
androidx-core-ktx = {
group = "androidx.core",
name = "core-ktx",
version.ref = "androidx-ktx"
}
androidx-appcompat = {
group = "androidx.appcompat",
name = "appcompat",
version.ref = "androidx-appcompat"
}
[plugins]
androidGradlePlugin = "com.android.tools.build:gradle:${androidGradlePlugin}"
- Versions — This section declares the versions of the dependencies and plugins that are used in the project.
- Library — This section declares the dependencies that are used in the project.
- Plugins — This section declares the plugins that are used in the project.
Add the version catalog file to your project
Once you have created the version catalog file, you need to add it to your project. To do this, open your project’s build.gradle
file and add the following code:
repositories {
//to download the JAR files for the dependencies from the Maven Central repository.
mavenCentral()
//to download the JAR files for the dependencies from the Gradle repository.
maven {
url "https://repo.gradle.org/gradle/libs-release"
}
}
dependencies {
implementation(libs.kotlin-stdlib)
implementation(libs.androidx-core-ktx)
implementation(libs.androidx-appcompat)
}
add below code to settings.gradle
to fetch the version catalog
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
Build your project
build your project and gradle will use the dependencies that are declared in the version catalog file to build your project. How easy it is?😍
Overall, Gradle version catalogs are a powerful tool that can help you to improve the performance, manageability, and collaboration of your Android builds. Therefore, if you are managing a large project with a lot of dependencies, Gradle version catalogs can be a great way to make your life easier.
If you have any query related to Android, I’m always happy to help you. You can reach me on Twitter and LinkedIn.