简体   繁体   English

科尔多瓦:在config.xml中使用环境变量

[英]Cordova: Use environment variables in config.xml

I believe exposing API secret key should be avoided. 我认为应该避免公开API密钥。 How can I use environment variable as a parameter in config.xml per a different environment during build time? 在构建期间,如何在每个不同的环境中将环境变量用作config.xml的参数?

For example, 例如,

<preference name="TwitterConsumerKey" value="$TWITTER_KEY" />
<preference name="TwitterConsumerSecret" value="$TWITTER_SECRET" />

Assumption: TWITTER_KEY and TWITTER_SECRET should be placed in dev and prod environment files with different values . 假设: TWITTER_KEYTWITTER_SECRET应该放在具有不同值的dev和prod环境文件中

I'm currently using a custom webpack configuration like below. 我目前正在使用如下所示的自定义Webpack配置。

const chalk = require("chalk");
const fs = require('fs');
const path = require('path');
const useDefaultConfig = require('@ionic/app-scripts/config/webpack.config.js');

let env = process.env.IONIC_ENV;

useDefaultConfig.prod.resolve.alias = {
  "@projectName/env": path.resolve(environmentPath('prod'))
};

useDefaultConfig.dev.resolve.alias = {
  "@projectName/env": path.resolve(environmentPath('dev')),
};

if (env !== 'prod' && env !== 'dev') {
  // Default to dev config
  useDefaultConfig[env] = useDefaultConfig.dev;
  useDefaultConfig[env].resolve.alias = {
    "@projectName/env": path.resolve(environmentPath(env))
  };
}

function environmentPath(env) {
  var filePath = './src/environments/environment' + (env === 'prod' ? '' : '.' + env) + '.ts';
  if (!fs.existsSync(filePath)) {
    console.log(chalk.red('\n' + filePath + ' does not exist!'));
  } else {
    return filePath;
  }
}

module.exports = function () {
  return useDefaultConfig;
};

What kind of things should I include in my custom configuration to make things happen? 我应该在我的自定义配置中包括什么样的东西才能使事情发生?

EDIT 编辑

environment.ts environment.ts

export const environment = {
  mode: 'Production',
  production: true,
  firebase: {
    apiKey: "SOME KEY",
    authDomain: "prod.firebaseapp.com",
    databaseURL: "https://prod.firebaseio.com",
    projectId: "prod",
    storageBucket: "prod.appspot.com",
    messagingSenderId: "SOME ID"
  },

  // I'd like to use these key values in config.xml during build time
  TWITTER_KEY: "SOME KEY", 
  TWITTER_SECRET: "SOME SECRET KEY"
};

environment.dev.ts environment.dev.ts

export const environment = {
  mode: 'Development',
  production: false,
  firebase: {
     apiKey: "SOME KEY",
     authDomain: "dev.firebaseapp.com",
     databaseURL: "https://dev.firebaseio.com",
     projectId: "dev",
     storageBucket: "dev.appspot.com",
     messagingSenderId: "SOME ID"
  },

  // Use these key values as well
  TWITTER_KEY: "SOME KEY", 
  TWITTER_SECRET: "SOME SECRET KEY"
};

For instance, ionic cordova build ios --dev will be using environment.dev.ts variables. 例如, ionic cordova build ios --dev将使用environment.dev.ts变量。 On the other hand, ionic cordova build ios --prod will be using environment.ts variables. 另一方面, ionic cordova build ios --prod将使用environment.ts变量。

I solved things like this simply by loading and parsing the config.xml (or whatever I needed, like .git/HEAD resp. ./git/refs/heads/* to get a latest commit hash) programmatically; 我可以通过编程方式简单地通过加载和解析config.xml (或我需要的任何东西,例如.git/HEAD./git/refs/heads/*来获取最新的提交哈希)来解决./git/refs/heads/* considering your environment.{dev,prod}.ts it could be (inside your webpack config): 考虑您的environment.{dev,prod}.ts可能是这样(在您的webpack配置中):

// just get the environment files:
const devEnvironment = require('/path/to/environment.dev.ts').environment;
const prodEnvironment = require('/path/to/environment.prod.ts').environment;

//...

const envConfig = env === 'prod' ? prodEnvironment : devEnvironment;

var twitterKey;
var twitterSecret;
// load the config.xml
var configXmlFile = fs.readFileSync(path.join(__dirname, './config.xml'));
// get it's rows
var configRows = configXmlFile.toString().split(/\n/);
// traverse the rows
configRows.forEach(function (row) {
    // check if the row do have what we're looking for
    if (row.indexOf('TwitterConsumerKey') !== -1) {
        // get the environment variable name
        var twitterKeyVarName = row.replace(/.*value="\$([^"]*)".*/, '$1');
        // get the variable value - environment file variant
        twitterKey = envConfig[twitterKeyVarName];
    }
    else if (row.indexOf('TwitterConsumerSecret') !== -1) {
        var twitterSecretVarName = row.replace(/.*value="\$([^"]*)".*/, '$1');
        twitterSecret = envConfig[twitterSecretVarName];
    }
});

Could probably be written in a more elegant way but that's the idea. 也许可以用一种更优雅的方式来写,但这就是想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM