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

Cordova允许插件有一个gradle文件,该文件可以与主文件合并,但是似乎只适用于模块的build.gradle,而不适用于项目的。

如何添加此classpath

最佳答案

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

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();
    });
};

该钩子(Hook)在config.xml中引用:

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

关于cordova - 在Cordova插件中将classpath添加到build.gradle,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51078719/

10-09 18:08
查看更多