Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: process.env has only NODE_ENV

Tags:

I'm setting an environment variable while building my react-native app (on windows):

SET APP_ENV=dev & react-native run-android

echo %APP_ENV% returns 'dev'

But when I log process.env object in my JS file, I only get:

{
  NODE_ENV: "development"
}

Is there a different way to access environment variables set through command prompt?

like image 928
Supreet Totagi Avatar asked Feb 24 '17 11:02

Supreet Totagi


People also ask

What is process env NODE_ENV?

NODE_ENV is an environment variable that stands for node environment in express server. The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production).

Can we use process env in react native?

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. They are not secure for various reasons.

What is the default NODE_ENV?

By default, the environment variable is unset and defaults to development. 1. process. env. NODE_ENV = process.

Does jest set NODE_ENV?

The next/jest preset sets NODE_ENV to 'production' . Users familiar with Jest will expect NODE_ENV to be 'test' when running tests. The documentation says: Set to 'test' if it's not already set to something else.


2 Answers

It's important to know that the React-Native app is running on a device (or emulator) in an environment more like a browser, not a Node.js process.

For cross-compatibility with Node.js libraries that relies on process.env.NODE_ENV to perform optimizations, React-Native adds the process global variable with env.NODE_ENV.

If you want to pass custom constants to React-Native, you can use: https://github.com/luggit/react-native-config

like image 60
lopezjurip Avatar answered Sep 20 '22 10:09

lopezjurip


You should install this plugin babel plugin

npm install babel-plugin-transform-inline-environment-variables --save-dev

Then add it to your babel config (.babelrc, babel.config.js) in the plugin section

{
  "plugins": [
    ["transform-inline-environment-variables", {
      "include": [
        "NODE_ENV"
      ]
    }]
  ]
}

Then when you pass the variable through the inline like

API_KEY=dev && react-native run-android

You should get it through

process.env.API_KEY

And the value will be dev

This work for me on Mac terminal, Hope it answer your question

EDIT: I added a double "&" because only one doesn't work.

like image 37
Hussam Kurd Avatar answered Sep 24 '22 10:09

Hussam Kurd