【问题标题】:Load different env variables with .env and create-react-app使用 .env 和 create-react-app 加载不同的环境变量
【发布时间】:2017-09-05 13:33:40
【问题描述】:

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

Dev/Prod Server     | .env file
---------------------------------------------
localhost           | .env.development.local
development         | .env.development
qa                  | .env.qa
production          | .env.production

所以,我尝试以这种方式编辑 package.json

"start-js": "react-scripts start .env.development.local",
"start": " npm-run-all -p watch-css start-js",
"build:dev": "npm run build-css && react-scripts build .env.development",
"build:qa": "npm run build-css && react-scripts build .env.qa",
"build:pro": "npm run build-css && react-scripts build .env.production"

但如果我执行build:* 命令,加载的文件始终是 .env.production,因为 NODE_ENV 是生产环境。是否可以使用"build:* 命令加载其他 .env 文件?

【问题讨论】:

  • 尝试查看 dotenv。您可以使用它加载不同的环境文件
  • @ReiDien 带有 dotenv 的 build:qa 的脚本应该是什么? npm run build-css && react-scripts dotenv_config_path=qa.env 不认识dotenv_config_path

标签: reactjs environment-variables create-react-app


【解决方案1】:

我是switchenv 的作者。它是一个命令行工具,用于从 Keepass 条目(来自 Notes 字段的内容)快速切换 .env 文件

只需运行 yarn switchenv development 即可替换您的 .env 文件。

运行 yarn switchenv production 并将您的 .env 文件替换为生产文件。

基本上,您所有的 .env 文件都作为条目存储在 Keepass 文件中。每个条目的 .env 文件的内容应存储在 Note 字段中。使用 switchenv 读取 Keepass 文件并将 .env 文件替换为条目的注释。

【讨论】:

    【解决方案2】:

    我使用 react-app-env 解决了我的问题并重命名了 .env 文件。

    Dev/Prod Server     | .env file
    ---------------------------------------------
    qa                  | qa.env
    

    例如,build:qa 脚本变成了:

    "build": "npm run build-css && react-scripts build",
    "build:qa": "react-app-env --env-file=qa.env build"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 2020-01-11
      • 2021-10-14
      • 2018-09-17
      • 2020-02-13
      • 2019-06-02
      • 1970-01-01
      相关资源
      最近更新 更多