如何在GitHub Action中读取package.json的版本号并作为变量使用
如何在GitHub Action中读取package.json的版本号并作为变量使用
我来帮你搞定这个问题!你需要先从仓库里的package.json中提取版本号,把它转成GitHub Action能识别的变量,之后就能在后续步骤里直接复用这个版本号了,不用每次手动改死版本号。具体操作分两步走:
第一步:新增提取版本号的步骤
在actions/checkout之后(只要能访问到package.json的位置就行),加一个步骤来读取package.json里的version字段,把它输出成Action的步骤变量。这里给你两种可选的方法:
方法1:用jq工具(MacOS Runner默认自带)
- name: 提取应用版本号 id: get_app_version run: echo "VERSION=$(jq -r '.version' package.json)" >> $GITHUB_OUTPUT
方法2:用Node/Bun来读取(更适合前端项目)
如果你担心runner里没有jq,也可以用Node或者你已经安装的Bun来读取:
# Node写法 - name: 提取应用版本号 id: get_app_version run: echo "VERSION=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT # 或者Bun写法 - name: 提取应用版本号 id: get_app_version run: echo "VERSION=$(bun -p "require('./package.json').version")" >> $GITHUB_OUTPUT
这里的id: get_app_version是给这个步骤起个标识,方便后续引用它的输出变量。
第二步:在Google Drive上传步骤中引用版本号变量
把原来写死的target: dist/app-2.0.1.dmg改成用变量拼接的形式,直接引用刚才提取到的版本号:
- uses: willo32/google-drive-upload-action@v1 if: startsWith(matrix.os, 'macos') with: target: dist/app-${{ steps.get_app_version.outputs.VERSION }}.dmg credentials: ${{ secrets.YOUR_GOOGLE_CREDENTIALS_SECRET }} # 记得改成你自己的Secret名称 parent_folder_id: some_id
完整修改后的Action配置
给你贴一下整合后的完整代码,直接替换原配置即可:
strategy: matrix: os: [macos-latest] steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v1 with: bun-version: "latest" # 新增的提取版本号步骤 - name: 提取应用版本号 id: get_app_version run: echo "VERSION=$(jq -r '.version' package.json)" >> $GITHUB_OUTPUT - name: Install dependencies run: bun install - name: Install NX run: bun i nx -g - name: Build MacOS if: startsWith(matrix.os, 'macos') run: nx run app:build-distro-mac-ci - uses: actions/upload-artifact@v4 if: startsWith(matrix.os, 'macos') with: name: app-mac path: dist/*.dmg retention-days: 7 - uses: willo32/google-drive-upload-action@v1 if: startsWith(matrix.os, 'macos') with: target: dist/app-${{ steps.get_app_version.outputs.VERSION }}.dmg credentials: ${{ secrets.YOUR_GOOGLE_CREDENTIALS_SECRET }} parent_folder_id: some_id
需要注意的是,得确保你的nx run app:build-distro-mac-ci构建命令生成的dmg文件名确实是app-<版本号>.dmg的格式,这样变量替换后的路径才会匹配到正确的文件。
备注:内容来源于stack exchange,提问作者tmptplayer
相关产品推荐
相关产品推荐

