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

如何让Cordova自动添加自定义Gradle依赖至build.gradle?

解决Cordova自动添加org.apache.http.legacy依赖的问题

针对你遇到的Cordova构建时build.gradle被覆盖、config.xml配置无效的问题,以下是几种可靠的解决方案:

方法一:使用项目级build-extras.gradle文件

Cordova支持读取项目根目录的自定义gradle配置文件,自动合并到生成的build.gradle中,步骤如下:

  1. 在项目根目录创建build-extras.gradle文件,写入内容:
dependencies {
    implementation "org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2"
}
  1. 在config.xml的Android平台配置块中添加引用:
<platform name="android">
    <!-- 其他配置 -->
    <gradleFile src="build-extras.gradle" />
</platform>

下次构建时,Cordova会自动将这个依赖注入到生成的build.gradle的dependencies块中。

方法二:使用Cordova构建钩子脚本

通过钩子脚本在构建流程中自动修改build.gradle文件,确保每次构建都会添加依赖:

  1. 在项目根目录创建hooks文件夹(若不存在)。
  2. 在hooks目录下创建before_build子目录,然后新建01_add_http_dependency.js文件,写入以下内容:
const fs = require('fs');
const path = require('path');

module.exports = function(context) {
    const buildGradlePath = path.join(context.opts.projectRoot, 'platforms/android/app/build.gradle');
    const dependencyLine = '    implementation "org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2"';

    fs.readFile(buildGradlePath, 'utf8', (err, data) => {
        if (err) throw err;
        if (!data.includes(dependencyLine)) {
            const updatedContent = data.replace(
                /dependencies {([\s\S]*?)}/,
                `dependencies {$1\n${dependencyLine}\n}`
            );
            fs.writeFile(buildGradlePath, updatedContent, 'utf8', err => {
                if (err) throw err;
            });
        }
    });
};
  1. 给脚本添加执行权限(Linux/macOS环境):
chmod +x hooks/before_build/01_add_http_dependency.js

Windows环境无需此步骤。

方法三:修改第三方插件的plugin.xml(若允许修改)

如果可以修改第三方插件的代码,直接在插件的plugin.xml中声明依赖,这样Cordova构建时会自动引入:
找到插件目录下的plugin.xml,在<platform name="android">块中添加:

<framework src="org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2" custom="true" type="gradleReference" />

注意:若插件通过npm安装,每次更新插件会覆盖修改,建议fork插件后修改再使用。

补充说明

之前你尝试的config.xml配置无效,可能是Cordova版本兼容性问题,部分旧版本对gradleReference类型的framework支持存在bug,上述三种方法均可绕过该问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 21:23:27