问题
I had updated cordova-android version to 6.4.0 and before that I had 5.1.1 installed. Here the problem was that when updated to 6.4.0 version, while building the project I was getting error. So to overcome that issue I had to add the below code
configurations.all {
resolutionStrategy {
force 'com.android.support:support-v4:27.1.0'
}
}
Now the problem is every time I build the project I have to edit build.gradle file, which is generated while adding the platform to the project in Cordova. As this is not part of Source Control.
To overcome this I have used the solution from this post. Here I am adding the Javascript file and adding the hook in the config.xml
Java script file
var fs = require('fs');
var rootdir = process.argv[2];
var android_dir = rootdir + '/platforms/android';
var gradle_file = rootdir + '/build-extras.gradle';
var dest_gradle_file = android_dir + '/build-extras.gradle';
if (fs.existsSync(android_dir) && fs.existsSync(gradle_file)) {
console.log('Copy ' + gradle_file + ' to ' + android_dir);
fs.createReadStream(gradle_file).pipe(fs.createWriteStream (dest_gradle_file));
} else {
console.log(gradle_file + ' not found. Skipping');
}
Build-extras.gradle
ext.postBuildExtras = {
android {
configurations.all {
resolutionStrategy {
force 'com.android.support:support-v4:27.1.0'
}
}
}
}
Hooks in Config.xml
<platform name="android">
<hook src="scripts/buildGradleHook.js" type="before_build" />
</platform>
The hooks added is not reflecting in the generated android folder. That is build-extras.gradle file is not reflected in android folder.
回答1:
I tried your solution and found that the vars declared to define the different paths are wrong.
I changed your hook code for this:
module.exports = function(ctx) {
var fs = ctx.requireCordovaModule('fs'),
path = ctx.requireCordovaModule('path'),
rootdir = ctx.opts.projectRoot,
android_dir = path.join(ctx.opts.projectRoot, 'platforms/android');
gradle_file = rootdir + '/build-extras.gradle';
dest_gradle_file = android_dir + '/build-extras.gradle';
/*
console.log("Before-Build Hook - rootdir", rootdir);
console.log("Before-Build Hook - android_dir", android_dir);
console.log("Before-Build Hook - gradle_file", gradle_file);
console.log("Before-Build Hook - dest_gradle_file", dest_gradle_file);
*/
if(!fs.existsSync(gradle_file)){
console.log(gradle_file + ' not found. Skipping');
return;
}else if(!fs.existsSync(android_dir)){
console.log(android_dir + ' not found. Skipping');
return;
}
console.log('Copy ' + gradle_file + ' to ' + android_dir);
fs.createReadStream(gradle_file).pipe(fs.createWriteStream(dest_gradle_file));
}
Also, in the Hook doc says it must be executable, so it needs to be wrapped by " module.exports = function(ctx) { }".
来源:https://stackoverflow.com/questions/51723145/add-custom-values-to-build-gradle-file-via-build-extras-gradle-in-cordova