Reactjs:在构建文件夹中使用 react build 设置 .env 文件,其中包含 3 个变量(prod、dev、staging)
Reactjs : set .env file with 3 variables(prod,dev,staging) in the build folder with react build
我有一个带有构建文件夹的 React 应用程序(由 npm 运行 build 生成),我想在我的 .env 文件中有 3 个变量(只有一个文件):
REACT_APP_API_URL=http://localhost:3000/api ( for production)
REACT_APP_PROD_URL=http://localhost:3001/api ( for staging)
REACT_APP_STAGIN_URL=http://localhost:3002/api ( for development)
并在 npm 运行 build 文件夹中使用它们
您需要为每个环境创建一个单独的 .env 文件。
如CRA Documentation: What other .env files can be used?所述:
.env.development, .env.test, .env.production: Environment-specific settings.
您不能将所有环境变量放在一个文件中,这些值将被覆盖。有关详细信息,请查看 dotenv
documentation
或者如果你想在构建项目后编辑环境变量,请参考:
试试 cross-env
你的 package.json
中有这样的东西
"start": cross-env REACT_APP_API_URL=http://localhost:3000/api node scripts/start.js
可能会帮助您实现目标
- 创建差异环境文件
- 安装
yarn add env-cmd
- 并将脚本添加到
package.json
:
"start-qa": "env-cmd -f .env.qa react-scripts start"
或构建:
"build-qa": "env-cmd -f .env.qa react-scripts build"
我有一个带有构建文件夹的 React 应用程序(由 npm 运行 build 生成),我想在我的 .env 文件中有 3 个变量(只有一个文件):
REACT_APP_API_URL=http://localhost:3000/api ( for production)
REACT_APP_PROD_URL=http://localhost:3001/api ( for staging)
REACT_APP_STAGIN_URL=http://localhost:3002/api ( for development)
并在 npm 运行 build 文件夹中使用它们
您需要为每个环境创建一个单独的 .env 文件。
如CRA Documentation: What other .env files can be used?所述:
.env.development, .env.test, .env.production: Environment-specific settings.
您不能将所有环境变量放在一个文件中,这些值将被覆盖。有关详细信息,请查看 dotenv
documentation
或者如果你想在构建项目后编辑环境变量,请参考:
试试 cross-env
你的 package.json
中有这样的东西"start": cross-env REACT_APP_API_URL=http://localhost:3000/api node scripts/start.js
可能会帮助您实现目标
- 创建差异环境文件
- 安装
yarn add env-cmd
- 并将脚本添加到
package.json
:
"start-qa": "env-cmd -f .env.qa react-scripts start"
或构建:
"build-qa": "env-cmd -f .env.qa react-scripts build"