Let you import
environment variables from a .env file in React Native, don't need any native code integration.
$ npm install react-native-dotenv --save-dev
Add the react-native-dotenv
preset to your .babelrc file at the project root.
{
"presets": ["module:metro-react-native-babel-preset", "module:react-native-dotenv"]
}
If you haven't got .babelrc set up for React Native, remember to install metro-react-native-babel-preset
first.
$ npm install metro-react-native-babel-preset --save-dev
Add your app configuration in an .env file. Prefix your values with $
to obtain from system env.
API_KEY=lorem
ANOTHER_CONFIG=foobar
ANOTHER_API_KEY=$API_KEY_FROM_SYSTEM_ENV
Now you can import it in your .js file.
import { API_KEY, ANOTHER_CONFIG, ANOTHER_API_KEY } from 'react-native-dotenv'
ApiClient.init(API_KEY, ANOTHER_CONFIG, ANOTHER_API_KEY)
As you can see, it's implemented as a babel plugin. All referenced imported members are replaced as the values or environment variables specified in the .env file
The example above will get compiled as below, assuming your system environment variable API_KEY_FROM_SYSTEM_ENV
is this_value_is_from_system_env
ApiClient.init('lorem', 'foobar', 'this_value_is_from_system_env')
Manually edit the file importing react-native-dotenv
by either adding an empty line or whitespace will work.
Yes, simply create a separate .env.production file and the default release process of react-native will pickup the right config.
You can use the Release configuration to launch the Simulator. (Only supported in RN v0.39+)
react-native run-ios --configuration Release
Command⌘
+M
to launch the developer menu in Android emulator.- Tap DevSettings.
- Toggle JS Dev Mode.
Sadly, it's not available so far. One of the workaround is generating .env file before triggering RN's bundle script automatically using either shell script or your own custom build pipeline.
MIT License, see LICENSE file for detail.