React 应用程序的运行时环境变量

Runtime environment variable for react app

我们有三个环境 DevStagingProd。 Create-react-app build 非常适合所有三种环境,但在构建过程中唯一发生变化的是 API 端点的环境变量。

我们在构建过程中使用 Jenkins 管道并将输出放在 S3 Bucket 中,该过程的唯一问题是我们必须为每个环境进行单独的构建,尽管除了API 环境变量。这需要花费大量时间。

所以我可能的解决方案是从编译环境变量移动到运行时环境。我遇到了 this。但我不知道如何做 JenkinsAWS

的新手

我们的文件夹结构如下所示

Project
|---mocks
|---static
|---index.html

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <!--
      manifest.json provides metadata used when your web app is added to the
      homescreen on Android. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">

    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React APP</title>
  </head>
  <body>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

所以,我正在写我们解决这个问题的方法。在 Jenkinfile 文件中,该文件位于我们的项目仓库中。我们对每个环境进行了以下更改。

在每个阶段之前,我们只需用相应的文件重写 env.js

 stage('Push to Dev') {
       ...
       steps {
         .....
           sh 'cp ./config/dev.js ./build/env.js'
            .....
       }
    }