Skip to content

Instantly share code, notes, and snippets.

@FranciscoG
Last active February 17, 2017 15:26
Show Gist options
  • Save FranciscoG/187b56cbc50a7eb0bf858ee7177eb341 to your computer and use it in GitHub Desktop.
Save FranciscoG/187b56cbc50a7eb0bf858ee7177eb341 to your computer and use it in GitHub Desktop.
Cordova hook to swap out variables in config.xml before preparing, building, or running. Useful to set different api keys per environment (staging, qa, production, etc)
#!/usr/bin/env node
/*****************************************************************
* I'm using this hook to set environment specific variables
*
* This hooks is executed before the following commands:
* cordova prepare
* cordova platform add
* cordova build
* cordova run
*/
const xml2js = require('xml2js');
const fs = require('fs');
const parseString = xml2js.parseString;
const builder = new xml2js.Builder();
const stagingDeploymentKey = "STAGING_KEY";
const productionDeploymentKey = "PROD_KEY";
/************************************************************
* load our commong config xml and parse it into a JS object
*/
var commonXML = fs.readFileSync(__dirname + '/../configs/common.xml').toString();
var commonObj;
parseString(commonXML, function (err, result) {
commonObj = result;
});
module.exports = function(context) {
// set API KEY to staging as default
var CodePushDeploymentKey = stagingDeploymentKey;
if (context.opts.options.release === true) {
// set API KEY to production
CodePushDeploymentKey = productionDeploymentKey;
}
/*******************************************************************/
// IMPORTANT NOTE:
// this will definitely be different for everyone.
// you'll have to do some testing to get the proper value location
commonObj.widget.platform[1].preference[0].$.value = CodePushDeploymentKey;
/*******************************************************************/
// write the xml file to the root director of the project so cordova can read it
var xml = builder.buildObject(commonObj);
fs.writeFileSync(__dirname + '/../config.xml', xml);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment