Passing values from Android/iOS or any other platform code should work, but it's a hassle.
Setting up Android to read values from properties and add those into BuildConfig, and do the equivalent in iOS?
Rather I'd like to do it once.
Yes(sort of).
Kotlin Multiplatform Project does not support product flavor. Kotlin/Native part of the project has release/debug
distinction, but it's not global.
So to mimick product flavor capability of Android, we need to provide additional property in order to determine flavors.
// ./mpp_project/build.gradlebuildkonfig {
packageName ='com.example.app'// default config is required
defaultConfigs {
buildConfigField 'STRING', 'name', 'value'
}
// flavor is passed as a first argument of defaultConfigs
defaultConfigs("dev") {
buildConfigField 'STRING', 'name', 'devValue'
}
targetConfigs {
android {
buildConfigField 'STRING', 'name2', 'value2'
}
ios {
buildConfigField 'STRING', 'name', 'valueIos'
}
}
// flavor is passed as a first argument of targetConfigs
targetConfigs("dev") {
ios {
buildConfigField 'STRING', 'name', 'devValueIos'
}
}
}
Kotlin DSL
importcom.codingfeline.buildkonfig.compiler.FieldSpec.Type.importcom.codingfeline.buildkonfig.gradle.TargetConfigDsl
buildkonfig {
packageName ="com.example.app"// default config is required
defaultConfigs {
buildConfigField(STRING, "name", "value")
}
// flavor is passed as a first argument of defaultConfigs
defaultConfigs("dev") {
buildConfigField(STRING, "name", "devValue")
}
targetConfigs(closureOf<NamedDomainObjectContainer<TargetConfigDsl>> {
create("android") {
buildConfigField(STRING, "name2", "value2")
}
create("ios") {
buildConfigField(STRING, "name", "valueIos")
}
})
// flavor is passed as a first argument of targetConfigs
targetConfigs("dev", closureOf<NamedDomainObjectContainer<TargetConfigDsl>> {
create("ios") {
buildConfigField(STRING, "name", "devValueIos")
}
})
}
In a development phase you can change value in gradle.properties as you like.
In CI environment, you can pass value via CLI $ ./gradlew build -Pbuildkonfig.flavor=release
Overwriting Values
If you configure same field across multiple defaultConfigs and targetConfigs, flavored targetConfigs is the strongest.
If you add a targetConfigs for appMain, you can't add configs for androidMain, desktopMain, or children of
desktopMain. This is because BuildKonfig uses expect/actual to provide different values for each BuildKonfig object.
When you provide a configuration for appMain, actual declaration of BuildKonfig object is created in `appMain. So any
additional actual declarations in children SourceSets leads to compile-time error.
Supported Types
String
Int
Long
Float
Boolean
Try out the sample
Have a look at ./sample directory.
# Publish the latest version of the plugin to mavenLocal()
$ ./gradlew publishToMavenLocal
# Try out the samples.
# BuildKonfig will be generated in ./sample/build/buildkonfig
$ ./gradlew -p sample generateBuildKonfig
请发表评论