React Native with Expo: how to use a .env.local config file?
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