DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Victor Rattis
Victor Rattis

Posted on

Tip: How to avoid duplicating Gradle codes in Multi Android modules

Let's assume the following code is added in more than one Android Gradle module on a project which has multiple Gradle modules.

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 30
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }
}
Enter fullscreen mode Exit fullscreen mode

To avoid duplicating this code in more than one module Gradle and avoid making mistakes, you could use the following solution:

Create a Gradle Script file in the root project, and for this code, you could create for example android.gradle and add the code common in it:

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 30
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }
}
Enter fullscreen mode Exit fullscreen mode

and in build.gradle of each Gradle module you can include it using apply from:'../android.gradle'. For example, including it into app/build.gradle.

apply from:'../android.gradle'

android {
    defaultConfig {
        applicationId "com.my.application"
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: