我正在尝试在 React 项目中设置不同的环境文件(使用 create-react-app)。我关注 official documentation但我收到一个错误:
'.env.development' is not recognized as an internal or external command,
我有 .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
时,两者都返回类似的错误。
我所有的 key 都以前缀开头:REACT_APP_。例如:REACT_APP_API_KEY
。
我错过了什么?
最佳答案
以下是您可以使用的 env 文件及其优先级(适用于 react-scripts@1.0.0
及更高版本):
.env
: Default.
.env.local
: Local overrides. This file is loaded for all environments except test.
.env.development
,.env.test
,.env.production
: Environment-specific settings.
.env.development.local
,.env.test.local
,.env.production.local
: Local overrides of environment-specific settings..
这意味着,production
的环境变量进入 .env.production
文件等。以下是要遵循的步骤:
创建你的
.env
或.env.production
文件...在项目的根目录中,与package 所在的文件夹相同.json
是。您在这些 env 文件中使用前缀
REACT_APP_
定义您的环境变量,如下所示:
REACT_APP_API_KEY=343535345235452452
- 然后以这种方式在代码中使用它们:
- In a JavaScript file:
process.env.REACT_APP_API_KEY
- In a HTML file:
<title>%REACT_APP_API_KEY%</title>
虽然如果你想在脚本
中设置一个环境变量,你可以这样做:
"scripts": {
"start": "REACT_APP_API_KEY=343535345235452452 react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
关于javascript - 使用 create-react-app react ,不同的 env 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71782533/