用 GitHub Actions 实现自动发布 NPM 包

一、前置条件

1.1 生成 NPM TOKEN

生成好了大概长这个样子 1c14ee16-xxxx-4ae3-b09f-faca87axxxx (注:已做脱敏处理)

1.2 加入 GitHub 项目的 secrets 里

二、编写 GitHub Actions 脚本

在你项目里创建 .github/workflows/main.yml 文件,内容如下:

name: Next release

on:
  push:
    branches: [ release ]
  pull_request:
    branches: [ release ]

jobs:
  publish-to-npm:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout release branch code
        uses: actions/checkout@v2
        with:
          fetch-depth: 1

      - name: Get yarn cache
        id: yarn-cache-dir-path
        run: echo "::set-output name=dir::$(yarn cache dir)"

      - name: Cache dependencies
        uses: actions/cache@v1.2.0
        id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
        with:
          path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-

      - name: Use Node.js
        uses: actions/setup-node@v1.4.2
        with:
          node-version: 12
          registry-url: https://registry.npmjs.org

      - name: Publish to NPM
        run: npm publish || true
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

#  publish-to-gpr:
#    runs-on: ubuntu-latest
#    steps:
#      - name: Checkout release branch code
#        uses: actions/checkout@v2
#
#      - name: Use Node.js
#        uses: actions/setup-node@v1.4.2
#        with:
#          node-version: 12
#          registry-url: https://npm.pkg.github.com/
#
#      - name: Publish to GitHub Package
#        run: npm publish
#        env:
#          NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

完整内容:https://github.com/Kennytian/tradex/blob/release/.github/workflows/main.yml

脚本解释:

  • 两个 release 表示向该分支 push 或提 PR 都会发布新的 NPM 版本
  • registry-url: https://registry.npmjs.org 表示 NPM 发布的目标地址(现在可向 GitHub 发 NPM 包)
  • npm publish || true 是不是特别熟悉,这其实是一条 Linux 命令,表示左边的命令执行失败,就执行后面的 true (这里有个坑,如果不加这个||,虽然能发布生成,但 Actions 一直会报错,让我很不解。如果您知道原因,请告之,错误详情:https://github.com/Kennytian/tradex/runs/640232951?check_suite_focus=true
  • NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 表示 NPM 发布调用 TOKEN,这个 TOKEN 就是我们向 GitHub 里添加的secrets 值

三、额外知识点

最近在学习 Linux,发现一个很好的视频教程,现分享给大家:https://www.bilibili.com/video/BV1mW411i7Qf?p=68

文中运用到的||,详解如下:

全文完!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。