Setting environment variable in 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.
Example:
development:
BASE_URL: '',
API_KEY: '',
staging:
BASE_URL: '',
API_KEY: '',
production:
BASE_URL: '',
API_KEY: '',
Solution 1:
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';
Solution 2:
The simplest (not the best or ideal) solution I found was to use react-native-dotenv. You simply add the "react-native-dotenv" preset to your .babelrc
file at the project root like so:
{
"presets": ["react-native", "react-native-dotenv"]
}
Create a .env
file and add properties:
echo "SOMETHING=anything" > .env
Then in your project (JS):
import { SOMETHING } from 'react-native-dotenv'
console.log(SOMETHING) // "anything"