如何在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
相关产品推荐
相关产品推荐

