Bitbucket 管道没有获取环境变量

Bitbucket pipelines not getting env variables

我正在使用 Bitbucket 管道将我的 React 应用程序部署到 s3 存储桶,部署工作正常,但不幸的是,我的 process.env 变量未定义。我已经在部署变量中添加了我所有的环境变量。

bitbucket-pipeline.yml:

image: node:14

pipelines:
  branches:
    master:
      - parallel:
        - step:
            name: Build and Test
            caches:
              - node
            script:
              - rm -rf package-lock.json
              - npm install
              - npm rebuild node-sass
              - CI=false npm run build:prod
            artifacts:
              - build/**
        - step:
            name: Security Scan
            script:
              # See more security tools at https://bitbucket.org/product/features/pipelines/integrations?&category=security
              - pipe: atlassian/git-secrets-scan:0.5.1
      - step:
          name: Deploy to Production
          deployment: Production
          trigger: manual
          clone:
            enabled: false
          script:
            # sync your files to S3
            - pipe: atlassian/aws-s3-deploy:1.1.0
              variables:
                AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
                AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
                AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION
                S3_BUCKET: $S3_BUCKET
                LOCAL_PATH: 'build'

build script in package.json

"build": "env-cmd -f .env.prod react-scripts build",

.env.prod

REACT_APP_BASE_URL=http://myurl/api

App.js

import { useEffect } from "react";
import axios from 'axios'

const App = () => {

    const getData = async () => {
        console.log("base url: ", process.env.REACT_APP_BASE_URL); // it is undefined
        const response = await axios.get(`${process.env.REACT_APP_BASE_URL}/api/users`);
        console.log("response: ", response)
    }

    useEffect(() => {
        getData();
    }, [])

    return <h1>My Component</h1>
};
}

问题是当我 运行 npm run build 在本地时,所以构建包含来自 .env.prod 的所有环境变量,因为该文件存在于我的本地机器中但在管道中我将所有 .env.prod 环境变量放在部署变量中,但不幸的是所有环境变量都是 undefined

React 在用户的网络浏览器中运行,因此无法访问服务器上的环境变量 运行。他们是不同的环境。

你可以embed environment variables in your app at build time:

Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

其中的“构建时”部分很重要。要在您的应用中包含和使用您的 REACT_APP_BASE_URL 变量,请确保以您的“构建和测试”步骤可以看到的方式定义它。

假设您已经为生产部署环境定义了该变量,请确保在构建步骤中使用该环境:

- step:
  name: Build and Test
  # Add this
  deployment: Production
  caches:
    - node
  script:
    - rm -rf package-lock.json
    - npm install
    - npm rebuild node-sass
    - CI=false npm run build:prod
  artifacts:
    - build/**

就我而言,在 Chris 的帮助下,我通过在存储库变量中添加所有环境变量解决了这个问题