问题描述
我正在使用react-native来构建跨平台应用程序,但是我不知道如何设置环境变量,以便可以为不同的环境使用不同的常量.
I am using react-native to build a cross-platform app, but I do not know how to set the environment variable so that I can have different constants for different environments.
示例:
development:
BASE_URL: '',
API_KEY: '',
staging:
BASE_URL: '',
API_KEY: '',
production:
BASE_URL: '',
API_KEY: '',
推荐答案
我建议您使用十二个因素建议让您的构建过程定义您的 BASE_URL
和 API_KEY
.
Instead of hard-coding your app constants and doing a switch on the environment (I'll explain how to do that in a moment), I suggest using the twelve factor suggestion of having your build process define your BASE_URL
and your API_KEY
.
要回答如何使环境暴露于 react-native
,我建议使用Babel的 babel-plugin-transform-inline-environment-variables .
To answer how to expose your environment to react-native
, I suggest using Babel's babel-plugin-transform-inline-environment-variables.
要使其正常工作,您需要下载插件,然后需要设置 .babelrc
,它的外观应如下所示:
To get this working you need to download the plugin and then you will need to setup a .babelrc
and it should look something like this:
{
"presets": ["react-native"],
"plugins": [
"transform-inline-environment-variables"
]
}
因此,如果您通过运行 API_KEY = my-app-id react-native捆绑包
(或start,run-ios或run-android)来转换您的react-native代码,那么您所拥有的全部要做的就是让您的代码看起来像这样:
And so if you transpile your react-native code by running API_KEY=my-app-id react-native bundle
(or start, run-ios, or run-android) then all you have to do is have your code look like this:
const apiKey = process.env['API_KEY'];
然后Babel将其替换为:
And then Babel will replace that with:
const apiKey = 'my-app-id';
希望这会有所帮助!
这篇关于在react-native中设置环境变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!