You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GitHub Action中按workflow_dispatch选项切换.env路径?能否用if语句?

如何根据GitHub Actions的workflow_dispatch输入切换.env文件路径?

当然可以用if语句实现,不过还有更简洁的方式,下面给你两种可行方案:

方案一:使用if条件拆分步骤

针对每个webpack-build-mode选项单独写一个步骤,通过if判断只执行匹配的步骤:

- name: Update API url (dev模式)
  if: ${{ github.event.inputs.webpack-build-mode == 'dev' }}
  uses: './.github/actions/replace-variable'
  with:
    orginal-variable: mydomain.com
    destination-variable: '${{ env.TARGET_DEV }}.mydomain'
    file-path: 'env/env.dev'

- name: Update API url (test模式)
  if: ${{ github.event.inputs.webpack-build-mode == 'test' }}
  uses: './.github/actions/replace-variable'
  with:
    orginal-variable: mydomain.com
    destination-variable: '${{ env.TARGET_DEV }}.mydomain'
    file-path: 'env/env.test'

- name: Update API url (production模式)
  if: ${{ github.event.inputs.webpack-build-mode == 'production' }}
  uses: './.github/actions/replace-variable'
  with:
    orginal-variable: mydomain.com
    destination-variable: '${{ env.TARGET_DEV }}.mydomain'
    file-path: 'env/env.prod'

这种方式适合不同模式需要调整其他参数(比如destination-variable)的场景,逻辑清晰,便于后续扩展。

方案二:直接用表达式映射路径(更简洁)

如果只有file-path需要变化,可以在步骤中直接用条件表达式生成路径,不需要拆分多个步骤:

- name: Update API url
  uses: './.github/actions/replace-variable'
  with:
    orginal-variable: mydomain.com
    destination-variable: '${{ env.TARGET_DEV }}.mydomain'
    file-path: ${{ 
      github.event.inputs.webpack-build-mode == 'dev' && 'env/env.dev' ||
      github.event.inputs.webpack-build-mode == 'test' && 'env/env.test' ||
      github.event.inputs.webpack-build-mode == 'production' && 'env/env.prod'
    }}

或者先通过run步骤设置环境变量,再引用,可读性更好:

- name: 设置.env文件路径
  run: |
    case "${{ github.event.inputs.webpack-build-mode }}" in
      dev) echo "ENV_FILE_PATH=env/env.dev" >> $GITHUB_ENV ;;
      test) echo "ENV_FILE_PATH=env/env.test" >> $GITHUB_ENV ;;
      production) echo "ENV_FILE_PATH=env/env.prod" >> $GITHUB_ENV ;;
    esac

- name: Update API url
  uses: './.github/actions/replace-variable'
  with:
    orginal-variable: mydomain.com
    destination-variable: '${{ env.TARGET_DEV }}.mydomain'
    file-path: '${{ env.ENV_FILE_PATH }}'

两种方案都能满足你的需求,根据实际场景选择即可。

内容的提问来源于stack exchange,提问作者shivetay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:23:38