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.
Example:
development:
BASE_URL: '',
API_KEY: '',
staging:
BASE_URL: '',
API_KEY: '',
production:
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
.
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';