【问题标题】:Cordova: Use environment variables in config.xmlCordova:在 config.xml 中使用环境变量
【发布时间】:2018-02-14 06:46:04
【问题描述】:

我认为应该避免暴露 API 密钥。在构建期间,如何根据不同的环境在 config.xml 中使用环境变量作为参数?

例如,

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

假设:TWITTER_KEYTWITTER_SECRET 应该放在具有不同值的 dev 和 prod 环境文件中

我目前正在使用如下的自定义 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;
};

我应该在我的自定义配置中包含哪些内容以使事情发生?

编辑

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

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"
};

例如,ionic cordova build ios --dev 将使用 environment.dev.ts 变量。另一方面,ionic cordova build ios --prod 将使用 environment.ts 变量。

【问题讨论】:

    标签: javascript cordova webpack environment-variables


    【解决方案1】:

    我通过以编程方式加载和解析config.xml(或我需要的任何东西,如.git/HEAD resp。./git/refs/heads/* 以获取最新的提交哈希)解决了这样的问题;考虑到您的 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];
        }
    });
    

    可能可以用更优雅的方式编写,但就是这样。

    【讨论】:

    • 您的代码如何从dev environment.tsprod environment.ts 中获取密钥和秘密值?
    • 我理解您的问题,因为您在 shell 变量中有密钥/秘密(如 value="$TWITTER_KEY" 形状所建议的那样);如果涉及environment.dev/prod.ts 文件,请向我们展示您如何将密钥/秘密存储在其中,无论如何我用建议的解决方案更新了答案
    • 我会试一试,然后再回复你。我应该将代码粘贴到自定义配置文件中的任何位置吗?
    • 另外,我想如何更改我的 config.xml 文件?只是把它作为问题?我说的是 config.xml 中的首选项名称和值
    • 建议将 import/require 语句放在文件的顶部,其余的您可以在使用收集的变量之前粘贴或将其包含在一个函数中以获得更好的清晰度(您甚至可以移动如果您愿意,可以转到另一个文件); config.xml 可能没问题(“变量”名称之前的 $ 符号是多余的,但如果您决定删除它们,请不要忘记从 row.replace 正则表达式中删除 \$)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    相关资源
    最近更新 更多