citrus327/issue-blog-record

使用Github Action自动发布npm包

Closed this issue · 0 comments

使用 Github Action 自动发布 npm 包

简介

下午抽空调研了一下如何使用 github action 来自动发布 npm 包。写下本文记录。

步骤

  • 准备 npm token
  • 设置 github secret
  • 设置 github actions

准备 npm token

  • 访问https://www.npmjs.com/ 并登录。
  • 进入个人设置 - access tokens。
  • 选择Generate New Token,输入密码确认。
  • 给该 token 起个名字(名字不影响,为了方便记忆可以使用npm_publish这种)。并设置 token 类型为Automation
  • 记下该 token。

设置 github secret

  • 进入 github 仓库。
  • 点击仓库的Settings - Actions,点击右上角的New Repository Secret
  • 输入 Token 名称,例如NPM_PUBLISH_TOKEN, 并填入之前在 npmjs.com 上创建的 npm token

设置 github actions

  • 在仓库内新建.github/workflows/publish.yml文件
  • 文件内容如下:
name: Publish to NPM
on:
  # release时触发。
  release:
    types: [created]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Setup Node
        uses: actions/setup-node@v3
        with:
          node-version: 16
      # 因为我的仓库使用的是pnpm,所以需要安装pnpm, 若使用的是npm则可以忽略。
      - name: Install Pnpm
        uses: pnpm/action-setup@v2.2.2
        with:
          version: 6.0.2
      # 安装依赖,脚本(run部分)可以自己写
      - name: Install dependencies
        run: pnpm install
      # 可以使用prepublishOnly来做build, 这样build可以在ci环节中剔除。见下文Tips
      - name: Build
        run: pnpm run build
      # 使用JS-DevTools/npm-publish@v1来进行npm发布。
      - name: Publish package on NPM 📦
        uses: JS-DevTools/npm-publish@v1
        with:
          # token里的secrets.NPM_PUBLISH_TOKEN就是在仓库内设定的token名。
          token: ${{ secrets.NPM_PUBLISH_TOKEN }}

测试使用

在 github 仓库的Releases页面点击Draft a new release
在一个 release 发布后,会自动触发上文设置的 github action。

Tips

  • 如果在package.json中设置了 prepublishOnly钩子去进行build操作,就无需在 action 中配置npm run build环节了。

Examples

参考:https://github.com/phshy0607/test-ci-auto-publish