Simon
Simon

Reputation: 6462

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?

Upvotes: 11

Views: 10917

Answers (2)

Pedram Vdl
Pedram Vdl

Reputation: 531

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

Upvotes: 5

Simon
Simon

Reputation: 6462

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));

Upvotes: 2

Related Questions