Kotlin多平台项目中enforcedPlatform函数的正确用法
报错原因
单平台JS项目的顶层dependencies块是Gradle原生作用域,默认导入了依赖相关的扩展函数,因此可以直接调用enforcedPlatform。
而Kotlin多平台项目中,sourceSets下各源集(如jsMain)的dependencies代码块是Kotlin Gradle插件自定义的KotlinDependencyHandler作用域,默认不会导入Gradle原生依赖处理器提供的enforcedPlatform、platform扩展函数,直接调用就会抛出Unresolved reference: enforcedPlatform错误。
修复方法
在enforcedPlatform调用前显式指定调用Gradle原生依赖处理器即可,也就是把原来的enforcedPlatform(xxx)改成dependencies.enforcedPlatform(xxx),完整可用配置如下:
plugins { kotlin("multiplatform") } kotlin { js(IR) { browser { commonWebpackConfig { cssSupport.enabled = true } } binaries.executable() } sourceSets { val jsMain by getting { dependencies { fun kotlinw(target: String): String = "org.jetbrains.kotlin-wrappers:kotlin-$target" implementation(dependencies.enforcedPlatform(kotlinw("wrappers-bom:1.0.0-pre.341"))) implementation(kotlinw("react")) implementation(kotlinw("react-dom")) implementation(kotlinw("css")) implementation(kotlinw("react-router-dom")) } } } }
注意事项
- 该写法完全支持通过BOM统一管理kotlin-wrappers版本,不需要给每个子依赖手动指定版本号,和单平台JS项目的使用效果没有区别
- 如果不需要强制版本对齐,要使用普通的
platform方法,也遵循同样的调用规则,写为implementation(dependencies.platform(/*BOM依赖坐标*/))即可
内容的提问来源于stack exchange,提问作者Jordi
相关产品推荐
相关产品推荐

