Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native with Expo: how to use a .env.local config file?

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?

like image 472
Simon Avatar asked Sep 27 '18 23:09

Simon


People also ask

Is .env a config file?

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.

How get data from env file in React Native?

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.


2 Answers

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));
like image 172
Simon Avatar answered Oct 09 '22 02:10

Simon


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
like image 44
Pedram Vdl Avatar answered Oct 09 '22 00:10

Pedram Vdl