我正在使用react-native来构建一个跨平台的应用程序,但我不知道如何设置环境变量,以便我可以有不同的常量为不同的环境。
例子:
development:
BASE_URL: '',
API_KEY: '',
staging:
BASE_URL: '',
API_KEY: '',
production:
BASE_URL: '',
API_KEY: '',
我正在使用react-native来构建一个跨平台的应用程序,但我不知道如何设置环境变量,以便我可以有不同的常量为不同的环境。
例子:
development:
BASE_URL: '',
API_KEY: '',
staging:
BASE_URL: '',
API_KEY: '',
production:
BASE_URL: '',
API_KEY: '',
当前回答
我使用babel-plugin-transform-inline-environment-variables。
我所做的是将配置文件放在S3中的不同环境中。
s3://example-bucket/dev-env.sh
s3://example-bucket/prod-env.sh
s3://example-bucket/stage-env.sh
每个env文件:
FIRSTENV=FIRSTVALUE
SECONDENV=SECONDVALUE
之后,我在包中添加了一个新脚本。Json,它运行用于捆绑的脚本
if [ "$ENV" == "production" ]
then
eval $(aws s3 cp s3://example-bucket/prod-env.sh - | sed 's/^/export /')
elif [ "$ENV" == "staging" ]
then
eval $(aws s3 cp s3://example-bucket/stage-env.sh - | sed 's/^/export /')
else
eval $(aws s3 cp s3://example-bucket/development-env.sh - | sed 's/^/export /')
fi
react-native start
在你的应用中,你可能会有一个配置文件,它有:
const FIRSTENV = process.env['FIRSTENV']
const SECONDENV = process.env['SECONDENV']
它将被巴别塔所取代:
const FIRSTENV = 'FIRSTVALUE'
const SECONDENV = 'SECONDVALUE'
记住你必须使用过程。env['STRING'] NOT process.env.STRING否则将不能正确转换。
其他回答
经过长时间的努力,我意识到react-native并没有正式提供这个功能。这是在babel生态系统中,所以我应该学习如何写一个babel插件…
/**
* A simple replace text plugin in babel, such as `webpack.DefinePlugin`
*
* Docs: https://github.com/jamiebuilds/babel-handbook
*/
function definePlugin({ types: t }) {
const regExclude = /node_modules/;
return {
visitor: {
Identifier(path, state) {
const { node, parent, scope } = path;
const { filename, opts } = state;
const key = node.name;
const value = opts[key];
if (key === 'constructor' || value === undefined) { // don't replace
return;
}
if (t.isMemberExpression(parent)) { // not {"__DEV__":name}
return;
}
if (t.isObjectProperty(parent) && parent.value !== node) { // error
return;
}
if (scope.getBinding(key)) { // should in global
return;
}
if (regExclude.test(filename)) { // exclude node_modules
return;
}
switch (typeof value) {
case 'boolean':
path.replaceWith(t.booleanLiteral(value));
break;
case 'string':
path.replaceWith(t.stringLiteral(value));
break;
default:
console.warn('definePlugin only support string/boolean, so `%s` will not be replaced', key);
break;
}
},
},
};
}
module.exports = definePlugin;
就这样,然后你可以这样用:
module.exports = {
presets: [],
plugins: [
[require('./definePlugin.js'), {
// your environments...
__DEV__: true,
__URL__: 'https://example.org',
}],
],
};
回答者提到的包也很棒,我也参考了metro-transform-plugins/src/inline-plugin.js。
对于最新的RN版本,您可以使用这个本机模块:https://github.com/luggit/react-native-config
[来源]从我的发现来看,默认情况下,它只可能做生产和开发配置(没有登台或其他环境)-对吗?
现在,我一直在使用一个environment.js文件,可以用来检测博览会发布通道,并根据此更改返回的变量,但对于构建,我需要更新返回的非DEV变量为staging或prod:
import { Constants } from 'expo';
import { Platform } from 'react-native';
const localhost = Platform.OS === 'ios' ? 'http://localhost:4000/' : 'http://10.0.2.2:4000/';
const ENV = {
dev: {
apiUrl: localhost,
},
staging: {
apiUrl: 'https://your-staging-api-url-here.com/'
},
prod: {
apiUrl: 'https://your-prod-api-url-here.com/'
},
}
const getEnvVars = (env = Constants.manifest.releaseChannel) => {
// What is __DEV__ ?
// This variable is set to true when react-native is running in Dev mode.
// __DEV__ is true when run locally, but false when published.
if (__DEV__) {
return ENV.dev;
} else {
// When publishing to production, change this to `ENV.prod` before running an `expo build`
return ENV.staging;
}
}
export default getEnvVars;
选择
谁有在用expo构建的项目中使用react-native-dotenv的经验?我很想听听你的想法
https://github.com/goatandsheep/react-native-dotenv
React native没有全局变量的概念。 它严格执行模块化范围,以促进组件的模块化和可重用性。
但是,有时您需要组件能够感知它们所处的环境。在这种情况下,定义一个环境模块非常简单,然后组件可以调用它来获取环境变量,例如:
environment.js
var _Environments = {
production: {BASE_URL: '', API_KEY: ''},
staging: {BASE_URL: '', API_KEY: ''},
development: {BASE_URL: '', API_KEY: ''},
}
function getEnvironment() {
// Insert logic here to get the current platform (e.g. staging, production, etc)
var platform = getPlatform()
// ...now return the correct environment
return _Environments[platform]
}
var Environment = getEnvironment()
module.exports = Environment
my-component.js
var Environment = require('./environment.js')
...somewhere in your code...
var url = Environment.BASE_URL
这创建了一个单例环境,可以从应用范围内的任何地方访问。你必须显式地要求(…)使用环境变量的任何组件的模块,但这是一件好事。
步骤1:像这样创建单独的组件 组件名称:pagebase.js 步骤2:在此使用代码this
export const BASE_URL = "http://192.168.10.10:4848/";
export const API_KEY = 'key_token';
步骤3:在任何组件中使用它,要使用它,首先导入这个组件,然后使用它。 导入并使用它:
import * as base from "./pagebase";
base.BASE_URL
base.API_KEY