首次使用Github Actions:按选择环境执行不同构建命令的实现方法
实现GitHub Actions按选择环境执行不同构建命令的思路
思路1:使用步骤级条件判断
直接在构建步骤中通过if条件匹配用户选择的环境,执行对应的构建命令,逻辑直观清晰:
jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install dependencies run: yarn install # 针对staging环境的构建 - name: Build for staging if: ${{ github.event.inputs.environment == 'staging' }} run: CI=false yarn build-staging # 针对non-prod环境的构建 - name: Build for non-prod if: ${{ github.event.inputs.environment == 'non-prod' }} run: CI=false yarn build # 可按需补充dev、prod环境的构建命令 - name: Build for dev/prod if: ${{ github.event.inputs.environment == 'dev' || github.event.inputs.environment == 'prod' }} run: CI=false yarn build # 替换为对应环境的构建命令
思路2:通过环境变量动态生成构建命令
先根据用户选择的环境设置对应的构建命令到输出变量,再统一执行,适合命令差异较小的场景,便于后续维护:
jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install dependencies run: yarn install - name: Determine build command id: build-command run: | case "${{ github.event.inputs.environment }}" in "staging") echo "command=CI=false yarn build-staging" >> $GITHUB_OUTPUT ;; "non-prod") echo "command=CI=false yarn build" >> $GITHUB_OUTPUT ;; "dev"|"prod") echo "command=CI=false yarn build" >> $GITHUB_OUTPUT # 替换为dev/prod的专属命令 ;; esac - name: Execute build run: ${{ steps.build-command.outputs.command }}
两种思路都能实现需求,你可以根据后续是否需要扩展更多环境命令来选择:如果每个环境的构建逻辑差异大,选思路1;如果只是命令后缀或参数不同,思路2更简洁。
内容的提问来源于stack exchange,提问作者Badari Kodegenahalli
相关产品推荐
相关产品推荐

