Reputation: 2246
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
?
Upvotes: 4
Views: 559
Reputation: 1003
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" />
Upvotes: 3