在 react-native 中设置环境变量? [英] Setting environment variable in react-native?
问题描述
我正在使用 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 bundle
(或 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 中设置环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!