我使用创建反应应用程序引导我的应用程序。

我添加了两个。env文件。env.development和。env。生产在根。

我的. environment .development包括:

API_URL=http://localhost:3000/api
CALLBACK_URL=http://localhost:3005/callback

当我运行我的应用程序使用反应脚本启动和控制台进程。环境,它吐出

{ NODE_ENV: "development", PUBLIC_URL: "" }

我尝试了不同的事情,但它只是不拾起我的开发文件,我做错了什么?!

领导结构为:

/.env.development
/src/index.js

包中。Json脚本是:

"start": "export PORT=3005; npm-run-all --parallel server:start client:start",
    "client:start": "export PORT=3005; react-scripts start",
    "server:start": "node server.js",
    "build": "react-scripts build",

编辑:

@jamcreencia正确地指出我的变量应该以REACT_APP为前缀。

编辑2

如果我将文件命名为。env,它就可以工作,但如果我使用。env.development或。end.production就不行


当前回答

对我有用的是在我的包中安装env-cmd。JSON添加以下代码行

"scripts": {
"start": "env-cmd -f .env.development react-scripts start ",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"

}

其他回答

第一步:

在你的。env。在本地文件中添加REACT_APP_your_API_key

第二步:

添加配置文件${process.env.REACT_APP_Your_API_key}

第三步:

必须重新启动React应用程序,然后测试它是否工作。

主要是我忘了最后一步

为此,有env-cmd模块。安装通过npm npm i env-cmd然后在你的包。Json文件在脚本部分:

  "scripts": {
    "start": "env-cmd .env.development react-scripts start",
    "build": "GENERATE_SOURCEMAP=false env-cmd .env.production react-scripts build",
  }

在你的项目根目录中,你必须创建两个env变量相同但值不同的文件:

.env.development
.env.production

那就把他们排除在公众之外。在你的.gitignore文件中添加两行:

.env.development
.env.production

因此,这是为dev和prod使用不同的env变量的正确方法。

关于env-cmd。根据VMois在gitHub上的帖子,env-cmd已经更新(编写时版本为9.0.1),环境变量将在你的React项目上工作如下:

"scripts": {
    "build:local": "env-cmd -f ./.env.production.local npm run build",
    "build:production": "env-cmd -f ./.env.production npm run build"
  }

在你的包裹里。json文件。

你的项目可以使用在你的环境中声明的变量,就像它们在你的JS文件中本地声明一样。默认情况下,您将拥有为您定义的NODE_ENV,以及以REACT_APP_开头的任何其他环境变量。

参考:https://create-react-app.dev/docs/adding-custom-environment-variables

那份文件造成了混乱。

所以你实际上需要在.env中放入前缀REACT_APP_才能使它工作。

并且确保重新启动测试/dev/prod服务器,因为.env内容更改是在构建阶段加载的。

当使用.env文件时,无论是前端还是后端。

每当修改.env文件时,必须重新启动相应的服务器,以便更改在应用程序中生效。 热重载不会从.env文件中读取更改。