【发布时间】:2018-02-14 06:46:04
【问题描述】:
我认为应该避免暴露 API 密钥。在构建期间,如何根据不同的环境在 config.xml 中使用环境变量作为参数?
例如,
<preference name="TwitterConsumerKey" value="$TWITTER_KEY" />
<preference name="TwitterConsumerSecret" value="$TWITTER_SECRET" />
假设:TWITTER_KEY 和 TWITTER_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