Reputation: 362
How to use .env in react . I can get access to .env.development and .env.production with
"start":"react-scripts start",
"build": "react-scripts build",
How to get access to another like .env.staging ?
I gave like this
"build_staging": "set REACT_APP_ENV=staging & react-scripts build",
but not working.
Any suggestions please.
Upvotes: 1
Views: 18329
Reputation: 1
[SOLUTION]: I've created env.js as shown below. env.js placement
after that i have added in index.html the script below
NB: i can acces my env.js var without import them (it seems the best way for me)
Upvotes: 0
Reputation: 1404
[CONTEXT]
- I've created React project with Create React
.
- Running on Windows 10
- Using VSCode IDE
- I have the file .env.development
on above /src
folder.
- My code has console.log(process.NODE_ENV)
and console.log(process.REACT_APP_YOUR_KEY)
[PROBLEM]
When I'm running the program with npm start
, the browser prints 'development' for NODE_ENV
, but for my React .env variable, it prints undefined
.
I try to run npm start
with changing the default script of package.json
to this start
script: set REACT_APP_YOUR_KEY && react-scripts start
. Then there isn't any undefined
, all works well. 🤨
[SOLUTION]
The cause was that the file .env.development
is not detected correctly. My hypothesis is the environment development file, Windows or VSCode don't detect well.
VS Code explorer. Look up the icon of the files 🤔
You have to change the file name from .env.development
to .env
.
Upvotes: 0
Reputation: 1636
To keep things consistent across linux(my production server) and windows(my development server) I use cross-env
npm install --save cross-env
and my scripts look like this
"scripts": {
"dev": "cross-env NODE_ENV=development node server",
"build": "cross-env NODE_ENV=production next build ",
"start": "cross-env NODE_ENV=production node server"
},
so to set a custom env like REACT_APP_ENV you'll need to
"build_staging": "cross-env REACT_APP_ENV=staging react-scripts build",
and you can access it in your javascript code using
process.env.REACT_APP_ENV
also to start a staging server you might want to add
"start_staging": "cross-env REACT_APP_ENV=staging react-scripts start"
more about this here
Upvotes: 5