首页 > 解决方案 > 是否可以创建引用公共模块的正确目标的 kotlin 多平台项目?

问题描述

如果我们想用 Kotlin 构建一个多平台项目,并且我们有这样的结构:

common
android
  android1
  android2
backend
  api1
  api2

common模块中,我们有 3 个目标/预设:

我们如何正确配置我们build.gradle的 s 文件以仅依赖于正确的预设/目标?

例如,如果我们想在我们的其他项目中使用 common 模块作为依赖项,我们需要使用类似的东西:

dependencies {
  implementation project(':common')
}

但是,是否可以只使用公共模块的正确部分?像这样的东西(对于android 1和2)?

dependencies {
  implementation project(':common:jvmAndroid')
}

否则,当我们使用implementation project(':common')它时,将获取所有 jvm 预设/目标,但某些代码仅在正确的平台上有意义或工作(在本例中为 android 或 api)。

标签: androidapikotlinbuild.gradlekotlin-multiplatform

解决方案


我们可以使用一种称为消除歧义的策略来实现这一目标。

https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html#disambiguating-targets

我们需要做类似的事情:

val commonAttribute = Attribute.of("com.example", String::class.java)

jvm {
    attributes.attribute(commonAttribute, "nameOfYourTarget")
}

在“客户端”和“服务器”端。以同样的方式。


推荐阅读