简体   繁体   English

将环境变量从 Package.json 传递给 React 应用程序

[英]Passing Environment variables to React application from Package.json

following this article https://serverless-stack.com/chapters/environments-in-create-react-app.html按照这篇文章https://serverless-stack.com/chapters/environments-in-create-react-app.html

I am trying to add an environment variable to my react app which I have created using create react app.我正在尝试将环境变量添加到我使用 create react app 创建的 react 应用程序中。 so my build command looks like below所以我的构建命令如下所示

 "build": "REACT_APP_SECRET_CODE=123 react-scripts build",

while I try to run this build command in my Visual studio code terminal via当我尝试通过以下方式在我的 Visual Studio 代码终端中运行此构建命令时

npm run build 

it gives me the error that REACT_APP_SECRET_CODE is not recognized as an internal or external command.它给了我一个错误,即REACT_APP_SECRET_CODE未被识别为内部或外部命令。

How would i pass the environment variable in `package.json and build my app and access the variable value in my app.我将如何在`package.json 中传递环境变量并构建我的应用程序并访问我的应用程序中的变量值。

you can do it in a clean way (imo) using better-npm-run package您可以使用Better-npm-run包以干净的方式(imo)

{
  "devDependencies": {
    "better-npm-run": "~0.0.1"
  },
  "scripts": {
    "build": "better-npm-run build",
  },
  "betterScripts": {
    "build": {
      "command": "react-scripts build",
      "env": {
        "REACT_APP_SECRET_CODE": "123"
      }
    }
  }
}

there are more advanced usage for this library, which I think might help you in the long term on your project这个库有更高级的用法,我认为从长远来看这可能对你的项目有帮助

If you don't want to install any other library.如果您不想安装任何其他库。 You can pass environment variable to yarn or npm command like this:您可以将环境变量传递给 yarn 或 npm 命令,如下所示:

"scripts": {
 "start": "breact-scripts start",
 "start:env": "REACT_APP_ABC=xyz yarn start",
}

Note: Remember to put prefix "REACT_APP_" in your environment variable otherwise React won't allow it to use in app.注意:请记住在您的环境变量中添加前缀“REACT_APP_”,否则 React 将不允许它在应用程序中使用。

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

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