首页 > 解决方案 > 在 React 应用程序中定义除默认 env 文件外的 .env 文件

问题描述

我需要为每个开发/生产服务器加载一个不同的 .env 文件。

localhost           | .env.localhost
development         | .env.development
production          | .env.production

基于 react 文档,默认情况下我们可以使用 .env.development 和 .env.production

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

但我想使用新的环境变量作为本地主机。我怎样才能做到这一点?我想通过 .env.localhost 变量的文件运行我的脚本之一。

标签: reactjsenvironment-variablescreate-react-app

解决方案


您可以从以下位置修改 package.json 的脚本部分:

"start": "react-scripts start"

对于 Linux 和 MacOS:

"start": "PORT=3006 react-scripts start"

窗口:

"start": "set PORT=3006 && react-scripts start"

如果你想在环境中设置新变量。然后在 shell 的 .env 文件中添加 then,但名称以 REACT_APP 开头

REACT_APP_MY_VAR


推荐阅读