Warm tip: This article is reproduced from serverfault.com, please click

Android Gradle declare a Variant Build Flavor dependency using API and Exclude in KTS

发布于 2021-01-14 20:49:22

I'm trying to build a flavor of my app that includes a very heavy dependency and is only going to be used in certain builds for testing and offline development (dependency is Wiremock for Android). However I can't seem to find any flavor variant dependency declarations that also use api() and exclude.

Before I decided to move the dependency to a build variant, I could declare the dependencies like so:

        dependencies {
            //WireMock - Do not put in release builds bc of large size
            api("com.github.tomakehurst:wiremock:2.18.0") {
                exclude("org.apache.httpcomponents", "httpclient")
                exclude("org.ow2.asm", "asm")
                exclude("org.json", "json")
            }
            api("org.apache.httpcomponents:httpclient-android:4.3.5.1")
        }

I would love to restrict this dependency to my build flavor, which I have simply called "mock", something like:

    dependencies: {
        "mockImplementation"(
               api("com.github.tomakehurst:wiremock:2.18.0") {
                    exclude("org.apache.httpcomponents", "httpclient")
                    exclude("org.ow2.asm", "asm")
                    exclude("org.json", "json")
            }
            api("org.apache.httpcomponents:httpclient-android:4.3.5.1")
        })
    }

This is obviously very wrong but I am unsure of how to go about formatting with the api and exclude dependency notations as I cannot find very many examples when it comes to also combining these with a build flavor.

Questioner
astralbody888
Viewed
0
astralbody888 2021-01-28 03:39:28

After a lot of playing around I ended up with:

// WireMock - Do not put in release builds bc of large size, restrict to mock flavors
"mockImplementation"(mockApi("com.github.tomakehurst:wiremock:2.18.0") {
    // Using Android Version Instead
    exclude("org.apache.httpcomponents", "httpclient")
    //Was getting a classpath conflict for org.objectweb.asm.AnnotationVisitor which is a part of 'net.minidev:asm'
    exclude("org.ow2.asm", "asm")
    //Was getting this warning, so decided to ignore this version included by WireMock.
    //Warning:Dependency org.json:json:20090211 is ignored as it may be conflicting with the internal version provided by Android.
    //In case of problem, please repackage with jar to change the class packages
    exclude("org.json", "json")
})
"mockImplementation"(mockApi("org.apache.httpcomponents:httpclient-android:4.3.5.1") {})

Note that the "mockApi" was necessary rather than just using "api" to actually constrain the variant.