简体   繁体   中英

Add classpath to build.gradle in cordova plugin

I'm writing a Cordova plugin, and I would like to add a classpath to the project's build.gradle , in the buildscript/dependencies section.

Cordova allows plugins to have a gradle file that gets merged with the main one, but it seems that that only works for the module's build.gradle , and not the project's.

How can I add this classpath ?

We had to accomplish the same and since it seems that Cordova does not have a built-in way to modify the main build.gradle file, we accomplished it with a pre-build 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();
    });
};

The hook is referenced in config.xml:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM