I have a react-native app running with expo (expo 27.1.1 and react-native 0.55.4).
I'd like to use a .env.local file, the only thing I found is using babel-plugin-inline-dotenv, but it loads the content of .env file instead of .env.local file (and I want it to load the content of .env.local if the file exists otherwise .env).
Is there an other similar plugin allowing that?
In case you are still wondering what all this means, well, you are probably new to the . env file. It's actually a simple configuration text file that is used to define some variables you want to pass into your application's environment.
All you have to do is write or define your variable in your root folder. Then, you can import the variable in your component before calling it. While env variables are very useful in React Native, it is not advisable to use them to store sensitive information like API keys, authentication keys, or passwords.
I finally found a solution:
Add a file env.js with this:
import Constants from "expo-constants";
function getEnvVars() {
if (__DEV__) {
return returnEnvVars();
} else {
return new Promise(resolve => {
resolve(Constants.manifest.extra);
});
}
}
async function returnEnvVars() {
return await import("envLocal.js");
}
export default getEnvVars;
Then you can put your env variables in the file envLocal.js
like this:
export default {
test: "localhost"
};
and your prod variables in your app.json
file, like this:
{
"expo": {
"extra": {
"test": "prod"
}
}
Finally you can call it like this:
import getEnvVars from "../environment";
getEnvVars().then(vars => console.log(vars));
Hi instead you can use Expo "extra" configuration property. in app.json under expo add let's say myApiKey like this:
{
"expo": {
"name": "login-app",
"slug": "login-app",
"privacy": "public",
"sdkVersion": "32.0.0",
"platforms": [
"ios",
"android"
],
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"updates": {
"fallbackToCacheTimeout": 0
},
"assetBundlePatterns": [
"**/*"
],
"ios": {
"supportsTablet": true
},
"extra": {
"myApiKey" : "1234"
}
}
}
And you can use it anywhere in your app without importing any file. just use it like this:
Expo.Constants.manifest.extra.myApiKey
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With