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

我添加了两个。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就不行


当前回答

如果你想使用多个环境,比如。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 

其他回答

如果你想使用多个环境,比如。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,因为我在node。js中就是这么做的。 在将名称更改为.env,重新启动终端,并再次运行npm start之后,一切都很顺利

对于最新的react-scripts(3.2.0)来说,这很简单

PORT=4000
BROWSER=none

在你的。env或。env.development文件(..etc)中,这应该是在根文件夹中。

它将无法使用REACT_APP前缀(我猜docs已经过时了),它不需要任何额外的npm包(react-scripts已经包含dotenv 6.2.0)

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

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

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

这是

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

但这是必须的

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