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
.
To answer how to expose your environment to react-native
, I suggest using Babel's babel-plugin-transform-inline-environment-variables.
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"
]
}
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'];
And then Babel will replace that with:
const apiKey = 'my-app-id';
Hope this helps!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…