简体   繁体   中英

How to use .env in react js

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.

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

[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.

Windows File Explorer files

VS Code explorer. Look up the icon of the files 🤔

You have to change the file name from .env.development to .env .

[SOLUTION]: I've created env.js as shown below. env.js placement

after that i have added in index.html the script below

my env.js content

NB: i can acces my env.js var without import them (it seems the best way for me)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM