React App的运行时环境变量

时间:2018-12-04 02:19:38

标签: reactjs jenkins amazon-s3 jenkins-pipeline create-react-app

我们有三个环境DevStagingProd。 Create-react-app构建非常适合所有三种环境,但是构建期间唯一改变的是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>

1 个答案:

答案 0 :(得分:1)

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

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

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