Reputation: 882
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?
Upvotes: 30
Views: 47603
Reputation: 9216
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.
Upvotes: 8
Reputation: 10590
Nothing worked out from these answers here, as well as React Native Expo Environment Variables, but I've found react-native-dotenv.
It did the trick:
yarn add react-native-dotenv --dev
babel.config.js
(or .babelrc
): add "module:react-native-dotenv"
to plugins
import { REST_API_KEY } from "@env";
at the topalert(REST_API_KEY);
Of course, with the alert
, that's a dummy example :)
Upvotes: 3
Reputation: 663
The easiest way I found to solve this problem is by using the react-native-config
library that you can have a look at here.
$ yarn add react-native-config
.env
file with your content. For example:GOOGLE_MAPS_API_KEY=abcdefgh
Config
from react-native-config
and use your variables.import Config from "react-native-config";
...
console.log('ENV:', Config.GOOGLE_MAPS_API_KEY); // ENV: abcdefgh
P.S.: After installing the package you need to run npx pod-install
to auto-link it or if your React Native version is older than 0.60, link it manually following the instructions on the library.
Upvotes: 3
Reputation: 424
add babel-plugin-transform-inline-environment-variables
npm install babel-plugin-transform-inline-environment-variables --save-dev
babel.config.js:
{
"plugins": [
["transform-inline-environment-variables"],
]
}
do not add "include": ["NODE_ENV"]
then run API_KEY=testKey && react-native start
and then you can use API_KEY
via process.env.API_KEY
,
but it is weird that console.log(process.env)
only show a {NODE_ENV: "development"}
,do not contain API_KEY
Upvotes: 2
Reputation: 383
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
Upvotes: 20