简体   繁体   中英

Using environment variables in ReactJS

So I've been setting up a new project and could not find any up-to-date explainations on how to do this, most people recommend to use dotenv but apparently dotenv is now included in react-scripts , how can I make use of this? where would I declare environment variables and how would I tell it to use production/environment ones when running my project? I know it seems like a "go read the documentation" question but I couldn't find any, and it's a pretty straight-forward question. TIA.

You can add properties in .env file in a key-value fashion

AWS_CRENDETIALS='asgashgash32612'

and reference them in your code with process.env.AWS_CRENDETIALS

You can inject these properties based on the environment you are having. So when you are in production, you simply overwrite these variables. Otherwise just read from .env file.

I personally don't use that file, but use in development a node command which has all the variables. In production they are managed by Azure DevOps for example.

Create a.env file in your root project directory with KEY=VALUE structure. Anywhere in your src/ you can access your variable with process.env.REACT_APP_KEY .

process.env is where all your ENV's are and CRA prefixes the custom ones with REACT_APP

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