This content originally appeared on Level Up Coding - Medium and was authored by Victor Bruce-Crabbe
Install react-native-dotenv library/package by running the command
npm i react-native-dotenv
For iOS,
- cd /ios
- pod install
Configure your babel.configure.js to allow you to inject your environment variables into your react-native environment using dotenv for multiple environments.
Basic Setup:
Inside your babel.configure.js file, add the code below:
module.exports = {
"plugins": [
["module:react-native-dotenv", {
"moduleName": "@env",
"path": ".env",
"blacklist": null,
"whitelist": null,
"safe": false,
"allowUndefined": true
}]
]
}
Usage:
Create a .env file in the root of your project folder and add your environment variables.
Next, import the environment variable and use it within your code like this:
For Projects using Typescript:
- Create a types folder
- Within the types folder create a file for example env.d.ts
- Open the tsconfig.json file and add the line below inside the “compilerOptions”: {} object:
"typesRoots": ["./src/types"]
- Now back to the env.d.ts file, declare an ‘@env’ module, add all your environment variables, and export like so:
Wrap Up:
In this blog post, we looked at how to use environment variables in our react-native project by installing the npm package react-native-dotenv and after, configure our babel.config.js file. Finally, we created an env file and imported the environment variable in the file/source code we want to use.
That will be it for now. Kindly give me your feedback in the comments section below. Thank you!
Using environment variables in a React Native App. was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Victor Bruce-Crabbe
Victor Bruce-Crabbe | Sciencx (2021-03-31T11:57:23+00:00) Using environment variables in a React Native App.. Retrieved from https://www.scien.cx/2021/03/31/using-environment-variables-in-a-react-native-app/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.