javascript - 使用 create-react-app react ,不同的 env 文件

标签 javascript node.js reactjs npm create-react-app

我正在尝试在 React 项目中设置不同的环境文件(使用 create-react-app)。我关注 official documentation但我收到一个错误:

'.env.development' is not recognized as an internal or external command,

我有 .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 时,两者都返回类似的错误。

我所有的 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 文件等。以下是要遵循的步骤:

  1. 创建你的 .env.env.production 文件...在项目的根目录中,与 package 所在的文件夹相同.json 是。

  2. 您在这些 env 文件中使用前缀 REACT_APP_ 定义您的环境变量,如下所示:

REACT_APP_API_KEY=343535345235452452

  1. 然后以这种方式在代码中使用它们:
  • 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/

相关文章:

debugging - 如何使用 PHPStorm 远程调试 Node JS?

node.js - 如何使用 list Node.js 站点进行缓存

javascript - 没有在状态中设置属性?

javascript - AJAX 在第一个表单之后不处理表单

php - 如何动态更改页眉和页脚?

javascript - 简单和基本的 Node WebSocket 客户端和服务器示例

reactjs - 找不到模块 : Error: Can't resolve 'fs' in dotenv - upgrading to react 17

javascript - Crossrider "appAPI.message.toAllTabs"方法的消息发送顺序

node.js - npm 包依赖项未安装

javascript - 组件(由 Route 创建)给出 inst.render is not a function 错误