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)