NOTE: npm react-native-dotenv is the new rewrite location
Let you import environment variables from a .env file in React Native, don't need any native code integration. This is the maintained fork of the abandoned repository.
$ npm install rn-dotenv --save-devAdd the rn-dotenv preset to your .babelrc file at the project root.
{
"presets": ["module:metro-react-native-babel-preset", "module:rn-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-devYou may have to reset cache before this works:
$ npm start -- --reset-cache
$ yarn start --reset-cache
$ npx react-native start --reset-cacheAdd your app configuration in an .env file.
API_KEY=lorem
ANOTHER_CONFIG=foobar
Now you can import it in your .js file.
import { API_KEY, ANOTHER_CONFIG } from 'rn-dotenv'
ApiClient.init(API_KEY, ANOTHER_CONFIG)If you're using this in a Typescript react native project, Typescript will complain that the named import does not exist in the package.
Here's a solution to solve the problem.
Steps
- Create a file
env.d.ts(The filename doesn't matter, as long it ends with.d.ts) - In the file write the following (for this example, I'll use
API_KEYas the environment variable)
declare module 'react-native-dotenv' {
/**
* API key
*/
export const API_KEY: string;
}- Now import the enviornment variable and your good to go. Ex:
import { API_KEY } from 'react-native-dotenv'
Solution provided by zetachang#76 (comment)
As you can see, it's implemented as a babel plugin. All referenced imported members are replaced as the values specified in the .env file.
The example above will get compiled as below.
ApiClient.init('lorem', 'foobar')Manually edit the file importing rn-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⌘+Mto 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.
When using a CI tool you will have to write the environment variables to the .env file. In Github Actions you may for example add a line like echo -e "${{ secrets.DOTENV }}" > .env.
MIT License, see LICENSE file for detail.