简体   繁体   English

如何在组件内部使用React自定义环境变量

[英]How to use React Customize Environment Variables inside component

I used Create-React-App to create a react application, now I want to have 3 different envirement variable for build : 我使用Create-React-App创建了一个React应用程序,现在我想为build创建3个不同的环境变量:

1 - Development 1-发展

2 - Staging 2-分期

3 - Production 3-生产

I follow this article from Facebook. 我关注Facebook上的这篇文章 So based on this artile, now I have 3 .env files in my project : 因此,基于这种弹头,现在我的项目中有3个.env文件:

.env.development

.env.staging

.env.production 

in each one of this .env files I have my API address based on the stage we are building the app, like this : 在每个.env文件中,我都有一个基于我们正在构建应用程序的阶段的API地址,如下所示:

API_URL=https://MYAPI.com/STAGE

in my package.json I have these scripts : 在我的package.json中,我有以下脚本:

"scripts": {
   "start": "env-cmd .env.development react-scripts start",
   "build_development": "env-cmd .env.development npm run build",
   "build_staging": "env-cmd .env.staging npm run build",
   "build": "react-scripts build",
 }

In my component which call this api URL, I use this to get the API_URL : 在调用此api URL的组件中,我使用它来获取API_URL:

let apiUrl = process.env.API_URL

So once I run for example : npm run build_staging 所以一旦我运行例如:npm运行build_staging

It will build the app but once I debug it, apiUrl is always undefined . 它将构建应用程序,但是一旦我对其进行调试, apiUrl始终是undefined

Not sure what is wrong? 不确定出什么问题了吗? anyone had such a problem? 有人遇到这样的问题吗?

I believe your environment variable names need to start with REACT_APP_ using create-react-app , as stated in the same GitHub page you linked. 我相信您的环境变量名称需要使用create-react-appREACT_APP_ ,如您链接的同一GitHub页面所述 Changing your API_URL to REACT_APP_API_URL should fix the issue. 将您的API_URL更改为REACT_APP_API_URL应该可以解决此问题。

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

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