Search code examples
kotlingradlegradle-plugingradle-kotlin-dsltoml

How to reference dependencies from libs.versions.toml file in a Gradle plugin


We have the following Gradle Version Catalog file libs.version.toml:

[libraries]
androidx-compose-material3 = { module = "libs.androidx.compose.material3", version = "1.2.1" }

How do I reference the above library inside a Gradle plugin:

class ExamplePlugin : Plugin<Project> {

    override fun apply(target: Project) {
        target.dependencies {
            implementation(libs.androidx.compose.material3)
        }
    }
}

I get an error: Unresolved reference: libs


Solution

  • Type-safe accessors from version catalogs are not (and will not be) available in regular class plugins, since such plugins are compiled in isolation.1

    You can access the version catalog in a non-type-safe fashion by using the VersionCatalogsExtension. For example (using Kotlin code with Kotlin DSL API):

    class ExamplePlugin : Plugin<Project> {
    
        override fun apply(target: Project) {
            val versionCatalog = target.the<VersionCatalogsExtension>().named("libs")
            target.dependencies {
                versionCatalog.findLibrary("androidx.compose.material3").ifPresent {
                    lib -> add("implementation", lib)
                }
            }
        }
    }
    
    

    This approach is mentioned in the Gradle documentation.

    Note: I've used the add syntax rather than implementation because I do not believe the implementation accessor is available inside a class plugin either (similarly to a version catalog, a class plugin could not be aware that such a configuration exists automatically).


    1 It looks Gradle has plans to bring them to the precompiled script plugins though, which you write in script files rather than regular code. See GitHub issue