解决 react-native-tts Android 构建失败:Could not find method jcenter()

解决 react-native-tts Android 构建失败:Could not find method jcenter()



在运行 React Native Android 项目时,我遇到了如下构建错误:

A problem occurred evaluating project ':react-native-tts'.

> Could not find method jcenter() for arguments [] on repository container of type

错误发生在执行以下命令时:

./gradlew app:installDebug

根据错误信息,问题最终定位到了以下文件:

node_modules/react-native-tts/android/build.gradle

问题原因分析

jcenter() 已经被 Gradle 官方弃用,并在较新的 Gradle 版本中被移除。

但部分较老的 React Native 第三方库仍然在 Android 配置中使用 jcenter(),这会直接导致 Android 构建失败。

本次出问题的正是 react-native-tts 这个库。


为什么不能直接改 node_modules?

直接修改 node_modules 中的代码虽然可以暂时解决问题,但并不可靠。

以下操作都会导致修改丢失:

  • 重新执行 npm install
  • 重新执行 yarn install
  • 删除并重建 node_modules

因此,我们需要一种可重复、可维护、对团队友好的解决方案。


正确的解决方案:patch-package

patch-package 是一个非常实用的工具,可以让我们对第三方依赖进行补丁修复,并在每次安装依赖时自动应用这些修改。

在 react-native-tts 官方修复之前,这是一个非常稳妥的方案。


修复步骤详解

1. 安装 patch-package

npm install patch-package --save-dev

或者使用 Yarn:

yarn add patch-package --dev

2. 修改 react-native-tts 的 Gradle 配置

打开以下文件:

node_modules/react-native-tts/android/build.gradle

找到 buildscript 中的 repositories 配置,将原来的:

buildscript {
    repositories {
        jcenter()
    }
}

修改为:

buildscript {
    repositories {
        google()
        mavenCentral()
    }
}

这样就移除了已废弃的 jcenter,并使用当前官方支持的仓库。


3. 生成补丁文件

在项目根目录执行:

npx patch-package react-native-tts

执行完成后,会生成类似如下的补丁文件:

patches/react-native-tts+X.Y.Z.patch

4. 配置自动应用补丁

package.json 中添加:

{
  "scripts": {
    "postinstall": "patch-package"
  }
}

这样每次安装依赖时,补丁都会自动生效。


5. 提交补丁文件

请将 patches/ 目录提交到版本控制系统中。

不要提交 node_modules


验证修复是否成功

可以通过以下步骤确认修复是否生效:

  1. 删除 node_modules
  2. 重新执行 npm installyarn install
  3. 再次运行 Android 构建

如果构建成功,说明补丁已正确应用。


总结

随着 Gradle 不断移除已废弃的功能,类似的问题会在旧版 React Native 库中越来越常见。

react-native-tts 官方修复之前,使用 patch-package 是一种干净、稳定且可维护的解决方案。

希望这篇文章能帮你节省一些排查问题的时间。🚀

❤️ Support This Blog


If this post helped you, you can support my writing with a small donation. Thank you for reading.


Comments

Popular posts from this blog

fixed: embedded-redis: Unable to run on macOS Sonoma

Copying MDC Context Map in Web Clients: A Comprehensive Guide

Reset user password for your own Ghost blog