简体   繁体   English

如何在使用 create-react-app 创建的应用程序中设置环境变量?

[英]How to set environment variables in app created with create-react-app?

I created an app with create-react-app and I'd like to configure some envs in JS files.我用create-react-app创建了一个应用create-react-app ,我想在 JS 文件中配置一些 envs。 Where should I put these files if I want them to be executed just after server initializing?如果我希望在服务器初始化后立即执行这些文件,我应该把这些文件放在哪里?

I've tried adding index.js to the root folder and creating server/config.js file, but that doesn't work.我已经尝试将index.js添加到根文件夹并创建server/config.js文件,但这不起作用。

if your purpose here is to check the application environment in the front end then no need set any .env file, you can just set global variables before running the script you need inside package.json file like that:如果您的目的是检查前端的应用程序环境,则无需设置任何 .env 文件,您只需在运行 package.json 文件中所需的脚本之前设置全局变量,如下所示:

"scripts": {
   "start": "REACT_APP_ENVIRONMENT=LOCAL react-scripts start"
   "build": "REACT_APP_ENVIRONMENT=PRODUCTION react-scripts build"
}

so whenever you want to work in your local environment you will run npm start and this will set REACT_APP_ENVIRONMENT variable to LOCAL value.因此,无论何时您想在本地环境中工作,您都将运行npm start ,这会将REACT_APP_ENVIRONMENT变量设置为LOCAL值。

and the same work when you want to run the application in production you run npm run build script and that will set the variable REACT_APP_ENVIRONMENT to PRODUCTION value当你想在生产中运行应用程序时,同样的工作你运行npm run build script 并将变量REACT_APP_ENVIRONMENT设置为PRODUCTION

you can use the same variables in your js config file to get the current environment like that:您可以在 js 配置文件中使用相同的变量来获取当前环境,如下所示:

export const isDevelopment = REACT_APP_ENVIRONMENT === 'LOCAL'; export const isProduction = REACT_APP_ENVIRONMENT === 'PRODUCTION';

Create a .env file in root directory of your app.在您的应用程序的根目录中创建一个 .env 文件。 Prefix every environment variable with the string REACT_APP_varNameHere.使用字符串 REACT_APP_varNameHere 为每个环境变量添加前缀。 Find examples here: https://create-react-app.dev/docs/adding-custom-environment-variables/在此处查找示例: https : //create-react-app.dev/docs/adding-custom-environment-variables/

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

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