Connect with us

Articles

Reducing Gradle boilerplate in multi-module Android projects

As an Android project collects more and more modules, we find ourselves duplicating lots of boilerplate in our Gradle build files.

As an Android project collects more and more modules, we find ourselves duplicating lots of boilerplate in our Gradle build files. This duplicate boilerplate wastes time, makes it more difficult to apply future changes, and increases our chances of introducing errors. Thankfully it is fairly simple to reduce this duplicate boilerplate.

Gradle build files for our modules have some unique settings like plugins and dependencies, but they also have lots of configuration options that are consistent across all modules. Most of our modules will specify a compile sdk version, minimum sdk version, test instrumentation runners, JVM target version, and perhaps lint options, packaging options, test options, and more. These are often identical across modules, so wouldn’t it be great if we could just write these once and share it across all of our modules? Here’s how.

In your project-level build.gradle.kts file, add an extension function BaseExtension.baseConfig(). This is where we will configure the settings that would have been inside the android {} block of our Android modules.

To apply these we need to add a second extension function:

And finally we need to wire these up to our actual modules:

Now your module-specific build files can look as simple as this

And that’s it!

Boilerplate reduced ✅

Advertisement

Trending