You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 01:48:33