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

如何在settings.gradle.kts中调用applyNativeModulesSettingsGradle

React Native 0.66.5集成Android项目(Kotlin Gradle)的自动链接问题

我正在将React Native 0.66.5集成到已上线的Android应用中,接近完成时遇到了一个问题:项目使用Kotlin Gradle而非Groovy,需要把一段Groovy代码转换为Kotlin版本并在settings.gradle.kts中执行。原Groovy代码如下:

apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)

我尝试了以下两种方案,但原生模块自动链接仍无法正常工作:

已尝试的无效方案

方案一

apply(from = file("./node_modules/@react-native-community/cli-platform-android/native_modules.gradle"))

方案二

val applyNativeModulesSettingsGradle: () -> Unit = {
    val nativeModulesGradleFile = File("./node_modules/@react-native-community/cli-platform-android/native_modules.gradle")
    if (nativeModulesGradleFile.exists()) {
        apply(from = nativeModulesGradleFile)
    } else {
        throw GradleException("native_modules.gradle not found in @react-native-community/cli-platform-android.")
    }
}

applyNativeModulesSettingsGradle()

正确的Kotlin写法

问题出在之前的方案只执行了引入脚本的步骤,漏掉了调用脚本中定义的applyNativeModulesSettingsGradle方法。正确的settings.gradle.kts代码应该是:

apply(from = file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"))
applyNativeModulesSettingsGradle(settings)

注意事项

  • 确认node_modules的路径是否正确:如果你的settings.gradle.kts位于Android项目的android目录下,而node_modules在项目根目录,那么使用../node_modules是正确的;如果路径不符,需要根据实际项目结构调整。
  • 引入脚本后,applyNativeModulesSettingsGradle方法会被脚本注入到当前上下文,直接调用并传入settings参数即可触发原生模块的自动链接逻辑。

内容的提问来源于stack exchange,提问作者Caue Sampaio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:10:11