我使用Bitbucket管道将我的react应用程序部署到s3桶中,部署工作正常,但不幸的是,我的process.env变量没有定义。我已经在部署变量中添加了我的所有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/apiApp.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变量,因为文件存在于本地机器中,但是在管道行中,我将所有.env.prod env变量放入部署变量中,但不幸的是,所有env变量都是undefined。
发布于 2022-03-01 15:01:24
React在用户的web浏览器中运行,因此无法访问服务器上运行的环境变量。它们是不同的环境。
注意:您必须创建以
REACT_APP_开头的自定义环境变量。除NODE_ENV以外的任何其他变量都将被忽略,以避免意外在机器上公开可能具有相同名称的私钥。。如果开发服务器正在运行,更改任何环境变量都需要重新启动它。
其中的“构建时”部分很重要。要在应用程序中包含和使用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/**发布于 2022-03-02 13:01:57
在我的例子中,在Chris的帮助下,我通过在存储库变量中添加所有环境变量来解决这个问题。
https://stackoverflow.com/questions/71309601
复制相似问题