在Cordova插件中将classpath添加到build.gradle

时间:2018-06-28 08:59:51

标签: cordova gradle build.gradle cordova-plugins

我正在编写一个Cordova插件,我想在classpath部分的项目build.gradle中添加一个buildscript/dependencies

Cordova允许插件具有与主要版本合并的gradle文件,但是看来这仅适用于模块的build.gradle,而不适用于项目的。

如何添加此classpath

1 个答案:

答案 0 :(得分:1)

我们必须完成相同的工作,并且由于Cordova似乎没有内置的方法来修改主build.gradle文件,因此我们使用了一个预构建钩子来实现它:

const fs = require("fs");
const path = require("path");

function addProjectLevelDependency(platformRoot) {
    const artifactVersion = "group:artifactId:1.0.0";
    const dependency = 'classpath "' + artifactVersion + '"';

    const projectBuildFile = path.join(platformRoot, "build.gradle");

    let fileContents = fs.readFileSync(projectBuildFile, "utf8");

    const myRegexp = /\bclasspath\b.*/g;
    let match = myRegexp.exec(fileContents);
    if (match != null) {
        let insertLocation = match.index + match[0].length;

        fileContents =
            fileContents.substr(0, insertLocation) +
            "; " +
            dependency +
            fileContents.substr(insertLocation);

        fs.writeFileSync(projectBuildFile, fileContents, "utf8");

        console.log("updated " + projectBuildFile + " to include dependency " + dependency);
    } else {
        console.error("unable to insert dependency " + dependency);
    }
}

module.exports = context => {
    "use strict";
    const platformRoot = path.join(context.opts.projectRoot, "platforms/android");

    return new Promise((resolve, reject) => {
        addProjectLevelDependency(platformRoot);
        resolve();
    });
};

该钩子在config.xml中引用:

<hook src="build/android/configureProjectLevelDependency.js" type="before_build" />