我尝试在一个React项目中设置不同的环境文件(使用create-react-app)。我按照官方文档,但我得到一个错误:
“. env.development”不被识别为内部或外部命令,
我的.env
、.env.local
、.env.development
、.env.production
与package.json
和src/
处于同一级别
我在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
。
我错过了什么?
2条答案
按热度按时间uqdfh47h1#
我想你必须使用env-cmd包才能使用多个env。这是最好的处理方式。只需按照此文档获取更多信息Multiple env example for react和env-Cmd package details
另外,请检查您在项目中使用的react/react-scripts版本,并检查您为演示创建的react/react-scripts版本是否适合您。
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.你可以这样在代码中使用它们:
如果你想在
scripts
中设置一个环境变量,你可以这样做: