Organize Gradle files with multi-module project

I have found a better way to organize Gradle files, it is useful for multi-module projects, where dependencies are duplicated. So instead of using a long list of implementations, we can group them into an array and import it as functions, here are the steps:

Step 1: Create a dependency.gradle file in your project level folder, in parallel with the project level build.gradle

Step 2: Import the settings in project level gradle

apply from: 'dependency.gradle'

buildscript {
apply from: 'dependency.gradle'

repositories {
...
}
dependencies {
classpath classpaths.values()
}
}

allprojects {
...
}

Step 3: Create the dependency.gradle file.

Note: the following is just an example, the actual gradle file is a lot longer

ext.versions = [
versionCode : 1,
versionName : "1.0.0",
minVersion : 21,
targetVersion : 27,
compileVersion : 27,
appId : "co.uk.yourappid",
gradle : "3.1.3",
kotlinGradlePlugin: "1.2.41",
googleServices : "3.2.0",

//android lib
supportLibrary : "27.1.1",
constraintLayout : "2.0.0-alpha1",
kotlin : "1.2.41",
googleServices : "3.2.0"

//third party
rxandroid : "2.0.1",
rxkotlin : "2.1.0"
]

ext.classpaths = [
gradle: "com.android.tools.build:gradle:$versions.gradle",
gradleKotlin: "org.jetbrains.kotlin:kotlin-gradle-plugin:$versions.kotlinGradlePlugin",
googleServices: "com.google.gms:google-services:$versions.googleServices"
]ext.files = [
files: fileTree(dir: 'libs', include: ['*.jar'])
]ext.local = [
tensorflow: project(':tensorflow'),
mlkit : project(':mlkit')
]

ext.androidLib = [
kotlin : "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$versions.kotlin",
support4 : "com.android.support:support-v4:$versions.supportLibrary"
]

ext.daggerKapt = [
daggerKapt : "com.google.dagger:dagger-compiler:$versions.dagger",
daggerAndroidKapt: "com.google.dagger:dagger-android-processor:$versions.dagger",
]

ext.daggerCompileOnly = [
glassfishCompileOnly: "org.glassfish:javax.annotation:$versions.annotation"
]

Step 4: Add the dependencies into your module level gradle as function, and we can finally view the gradle file in one screen without scrolling up and down, hooray!

apply plugin: 'com.android.library'
...

android {
compileSdkVersion versions.compileVersion
defaultConfig {
minSdkVersion versions.minSdkVersion
targetSdkVersion targetSdkVersion
...}
}

dependencies {
implementation files.values()
implementation androidLib.values()
implementation rxjava.values()
implementation dagger.values()
compileOnly daggerCompileOnly.values()
kapt daggerKapt.values()
implementation picasso.values()
implementation mlkit.values()
}

You can find the full code here.


Posted

in

by

Tags: