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

我添加了两个。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"

}

其他回答

如果你想使用多个环境,比如。environment .development . environment .production

使用dotenv-cli包

添加.env.development和.env。项目根文件夹中的生产

还有package.json

"scripts": {
    "start": "react-app-rewired start",
    "build-dev": "dotenv -e .env.development react-app-rewired build",
    "build-prod": "dotenv -e .env.production react-app-rewired build",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
    "eject": "react-scripts eject"   
},

然后根据环境来建造

npm run-script build-dev 

我也遇到了同样的问题,但这是因为我的.env文件是YAML格式而不是JS格式。

这是

REACT_APP_API_PATH: 'https://my.api.path'

但这是必须的

REACT_APP_API_PATH = 'https://my.api.path'

我有同样的问题,我无法在App.js中访问.env变量。 我已经解决了使用创建正确的。env文件的问题。

在我的情况下,我从不同的操作系统复制文件,并在ubuntu系统中使用 所以我只是做“sudo touch .env”,并添加我的变量,重新启动应用程序,然后它为我工作。

对于任何VS Code用户,请注意.env. conf文件。本地env文件是自动获取的,但当你在项目范围内搜索MY_ENV_VAR时,也会从搜索结果中自动忽略(可能是因为默认情况下git忽略了它)。这意味着如果你的.env. var =中有MY_ENV_VAR=。像我这样的当地人忘记了它,它会破坏东西,你会花15分钟非常困惑。

如果。env文件工作,但是。env.development或。env.development。然后在这两个文件旁边创建一个空的.env文件。我不知道为什么,但这对我来说很管用。