Lahiru Chandima
Lahiru Chandima

Reputation: 24068

Share compile dependencies across modules

I have an android project with two modules. Both modules depend on android support library. Currently the support library dependency is added to gradle scripts of both modules.

When I upgrade support library version, I have to upgrade the version in both gradle files. I may sometimes forget to do this in both files. So I need a way to declare the support version in a one common place.

This page describes one approach, where you declare the dependencies in a separate file and include it in the root gradle file.

This approach worked for me, but there are some limitations. For an example, if a new support library is available, in previous approach, android studio gave me an inspection warning that a newer version is available. With new approach, android studio no longer does that. Also, whenever you make a change in a gradle file, android studio asks for re-sync the project. But, if I made change to the separated gradle dependency file, android studio doesn't ask me to re-sync.

I tried to directly add the support dependencies to the dependencies section of the root gradle file like given below, but android studio gives me a warning.

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'
        compile "com.android.support:appcompat-v7:23.2.1"
    }
}

Warning:

Fix plugin version and sync project.

Does anyone know any other ways which I can declare dependencies in a central place?

Upvotes: 0

Views: 180

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317352

The easiest thing to do is declare an extension variable in your buildscript block that manages the entire build. Let's take a Kotlin project, for example, where the version of kotlin must be consistent between all the build components. Here's a top-level build.gradle that defines the buildscript:

buildscript {
    ext.kotlin_version = '1.0.1'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Notice that it defines ext.kotlin_version, then uses it below in the plugin dependency.

Then, in the main app module:

dependencies {
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

I can use the variable again to use the same version of the kotlin stdlib compile dependency. But I only had to define the version string in one place. ext is a special gradle way of declaring extra properties for gradle domain objects. Defining one in buildscript makes it visible elsewhere for use.

Upvotes: 2

Related Questions