我正在编写一个Cordova插件,我想在其中添加一个 classpath
到项目的 build.gradle
,在 buildscript/dependencies
部分。
Cordova允许插件拥有一个与主文件合并的gradle文件,但这似乎只适用于模块的 build.gradle
,而不是项目的。
我如何添加这个 classpath
?
我们必须完成同样的任务,由于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" />