.env
我使用 data 在目录的根目录中创建了文件REACT_APP_API_URL=http:\\localhost:3001
,但是当我运行并从中获取值时process.env
,我得到一个空对象,我该如何解决?
1004 次
1 回答
1
您需要将变量与启动脚本集成。
"scripts": {
"start": "REACT_APP_API_URL=http://localhost:3001 react-scripts start", //like this
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
那么你需要运行你的应用程序。它将需要所有参数。
或者使用命令行传递它的另一种运行方式。例如:您需要在加载脚本之前先传递 env 变量
REACT_APP_API_URL=http://localhost:3001 npm start
您还可以使用包进行更好的 env 管理(cross-env)它将负责所有与 env 相关的管理。随时检查那里的文档。
如果你想使用跨环境,你只需要从 .env 文件运行环境(注意:.env 文件应该在 package.json 级别)
"scripts": {
"start": "cross-env react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
它会在您想使用时从 .env 文件中加载您的所有配置。
于 2019-05-19T05:57:59.950 回答