Environment variables in config.xml?

I need to have some environment variables in config.xml, or an equivalent way to dynamically set values in that file. What is the recommended approach for something like this?

Just as an example, suppose I need to decide the widget version setting at build time, etc.

Thanks!

2 Likes

Following are the steps that can help:

  1. If we need to change the variables in config.xml file as per the passed environment like dev, prod, qa etc then we should have separate file like environment.ts, environment.prod.ts, environment.qa.ts etc.

environment.ts

export const environment = {
"appId": "io.ionic.starterDev",
"appName": "App Dev",
"version": "0.0.1",
};

environment.prod.ts

export const environment = {
"appId": "io.ionic.starterProd",
"appName": "App Prod",
"version": "0.0.1",
};
  1. Next we need to write a gulp task that will read passed environment and improve the config.xml accordingly as per the environment variables.

  2. For that we need to install cordova-config and gulp then create gulp.js file.

gulp.js

const gulp = require('gulp');
const Config = require('cordova-config');
let fs = require('fs');
let argv = require('yargs').argv;
gulp.task('config', async function () {
    let data;
    let env = argv.channelTag;
    if (!env || env === 'dev') {
        data = fs.readFileSync('src/environment.ts', 'utf-8');
        console.log('Environment configured for dev')
    } else {
        data = fs.readFileSync(`src/environment.${env}.ts`, 'utf-8');
        /* To change the environment as per the passed flag.
           ie. if prod is passed then environment.prod.ts file will be copying in environment.ts file
        */
        fs.writeFileSync('src/environment.ts', data, 'utf-8');
        console.log('Environment configured for ' + env);
    }
    let startIndex = data.indexOf("{");
    let lastIndex = (data.lastIndexOf("}")) + 1;
    let configEnv = JSON.parse(data.substring(startIndex, lastIndex))
    const configXml = new Config('config.xml');
    configXml.setID(configEnv.appId);
    configXml.setName(configEnv.appName);
    configXml.setVersion(configEnv.version);
    configXml.writeSync();
});
  1. Then we need to run ‘cordova plugin save’ command then run ‘gulp config --channelTag=<dev/prod/qa>’

  2. If channelTag is not passed with the command then config.xml will be updated as per the dev environment.

  3. Now the environment and config.xml file is updated as per the passed environment hence we can build the app.

HTH!

3 Likes