NodeJS React,使用create-react-app创建不同的env文件

brc7rcf0  于 2023-06-22  发布在  Node.js
关注(0)|答案(2)|浏览(169)

我尝试在一个React项目中设置不同的环境文件(使用create-react-app)。我按照官方文档,但我得到一个错误:
“. env.development”不被识别为内部或外部命令,
我的.env.env.local.env.development.env.productionpackage.jsonsrc/处于同一级别
我在package.json中的脚本:

"scripts": {
   "start": "react-scripts start",
   "build": "react-scripts build",
   "test": "react-scripts test",
   "eject": "react-scripts eject"
},

还尝试了其他选项:"start": ".env.local, .env.development, .env"
当我运行npm start时,两者都返回类似的错误。
我所有的密钥都以前缀开头:REACT_APP_.例如:REACT_APP_API_KEY
我错过了什么?

uqdfh47h

uqdfh47h1#

我想你必须使用env-cmd包才能使用多个env。这是最好的处理方式。只需按照此文档获取更多信息Multiple env example for reactenv-Cmd package details
另外,请检查您在项目中使用的react/react-scripts版本,并检查您为演示创建的react/react-scripts版本是否适合您。

dgtucam1

dgtucam12#

以下是您可以使用的env文件及其优先级(可用于react-scripts@1.0.0及更高版本):
.env:默认。
.env.local:本地覆盖。除测试环境外,所有环境都加载此文件。
.env.development.env.test.env.production:特定于环境的设置。
.env.development.local.env.test.local.env.production.local:环境特定设置的本地覆盖。
这意味着production的一个环境变量放在.env.production文件中,等等。以下是要遵循的步骤:
1.创建.env.env.production文件...在项目的根目录中,与package.json所在的文件夹相同。
1.在这些env文件中使用前缀REACT_APP_定义环境变量,如下所示:
REACT_APP_API_KEY=343535345235452452
1.你可以这样在代码中使用它们:

  • 在JavaScript文件中:
process.env.REACT_APP_API_KEY
  • 在HTML文件中:
<title>%REACT_APP_API_KEY%</title>

如果你想在scripts中设置一个环境变量,你可以这样做:

"scripts": {
    "start": "REACT_APP_API_KEY=343535345235452452 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
},

相关问题