【问题标题】:Environment variables for React Application at runtimeReact 应用程序在运行时的环境变量
【发布时间】:2021-07-29 08:38:23
【问题描述】:

我有一个要部署到 Cloud Foundry 的 React 应用程序。我想隔离开发、舞台和产品。问题是 React 为react-scripts start 提供了.env.development,为react-scripts build 提供了.env.production

我想要一个在运行时拥有 3 个独立环境的解决方案(使用 npm build

我已经加了app-config.js:


const SPACE_NAME_JSON = process.env.VCAP_APPLICATION
const SPACE_NAME = JSON.parse(SPACE_NAME_JSON).space_name

if (SPACE_NAME.match(/development/)) {
    process.env.NODE_ENV = 'development'
} else if (SPACE_NAME.match(/stage/)) {
    process.env.NODE_ENV = 'stage'
}
} else if (SPACE_NAME.match(/production/)) {
    process.env.NODE_ENV = 'production'
}

console.log(`${process.env.NODE_ENV}`)

package.json:build": " react-scripts build && cp app-config.js ./build"

并在运行时将脚本注入public/index

<script src="%PUBLIC_URL%/app-config.js">
</script>

但是在运行应用程序之后,process.env.NODE_ENV 给了production 而不是development 用于开发环境。这意味着它默认为 CRA 的环境。

有没有办法在不弹出 webpack 的情况下做到这一点。 (因为 webpack 在构建时发生,但应用程序在运行时获取详细信息。

【问题讨论】:

  • 我想我读到 NODE_ENV 是只读的。看看here

标签: node.js reactjs environment-variables cloud-foundry


【解决方案1】:

您可以在提供关注之前编写脚本来更改您的文件 - https://dev.to/akdevcraft/react-runtime-variables-49dc,或者使用执行此操作的软件包 https://github.com/andrewmclagan/react-env

示例代码将在以下行中

// .env file
# .env
REACT_APP_NEXT="Next.js"
REACT_APP_CRA="Create React App"
REACT_APP_NOT_SECRET_CODE="1234"

// Your code
import env from "@beam-australia/react-env";

export default (props) => (
  <div>
    <small>
      Works in the browser: <b>{env("CRA")}</b>.
    </small>
    <small>
      Also works for server side rendering: <b>{env("NEXT")}</b>.
    </small>
    <form>
      <input type="hidden" defaultValue={env("NOT_SECRET_CODE")} />
    </form>
    <small>
      Entire safe environment:
      <pre>
        <code>{{JSON.stringify(env())}}</code>
      </pre>
    </small>
  </div>
);

// package.json
{
  ...
  "scripts": {
    "start": "react-env --env APP_ENV -- next start" // where .env.${APP_ENV}
  }
  ...
}

需要很少的其他配置步骤,您可以在包帮助中找到这些步骤

【讨论】:

    猜你喜欢
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2021-10-25
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多