React env variables with .env

血红的双手。 提交于 2019-12-29 00:33:14

问题


I'm trying to follow docs on adding env variables from react-create-app without success:

https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-custom-environment-variables

  • inside root of the document I have a ".env" file (default .env properties)
  • .env file contains only one variable 'REACT_APP_API_HOST=http://localhost:8080'
  • trying to access process.env inside my app (created with create react app) gives me undefined

This is app.js where I'm trying to access process.env without success.

I can't access process.env inside the code. Is there any working example on how to do it?


回答1:


You can use .env file on root.

  • start: react-scripts start - uses .env.development
  • build_staging: "set REACT_APP_ENV=staging & react-scripts build" - uses .env.staging
  • build: "react-scripts build" - uses .env.production



回答2:


In your package.json you will eventually have to add NODE_ENV=development at your start script. E.g. NODE_ENV=development && node scripts/start.js for the ejected create-react-app and NODE_ENV=development react-scripts start for the unejected one.

Edit: Apparently NODE_ENV=development is not required since it is already hardcoded when you run the start or build script. Per the docs your custom environment variables should have the following format REACT_APP* as you have already done.

A snippet would be helpful.



来源:https://stackoverflow.com/questions/44389288/react-env-variables-with-env

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!