简体   繁体   English

根据环境反应配置变量

[英]React configure variables based on environment

In my react app, I have a component say chart in which an external API is called.在我的 React 应用程序中,我有一个组件 say chart,其中调用了外部 API。

While running in the local, the API URL will be localhost:8080 When deployed and the API URL should be prod:8080在本地运行时,API URL 将是localhost:8080部署时,API URL 应该是prod:8080

The examples based on.env uses process.env and inside the component where the API is called process is undefined.基于.env 的示例使用 process.env 并且在 API 称为进程的组件内部未定义。

Is there a way to access the env file inside the component which runs on the browser.有没有办法访问在浏览器上运行的组件内的 env 文件。

If you are using CRA:如果您使用 CRA:

React's documentation on environment variables: React 关于环境变量的文档

"Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_. " “您的项目可以使用在您的环境中声明的变量,就好像它们是在您的 JS 文件中本地声明的一样。默认情况下,您将为您定义 NODE_ENV,以及任何其他以REACT_APP_.

Otherwise you might use something like dotenv and import it in your application index.tsx否则你可能会使用类似dotenv的东西并将它导入你的应用程序index.tsx

For your specific use case, you also want to have 2 .env files since you want one for development and production .对于您的特定用例,您还需要 2 个.env文件,因为您需要一个用于developmentproduction So take a look a this .所以看看这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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