用 GitHub Actions 實(shí)現(xiàn)自動發(fā)布 NPM 包

一、前置條件

1.1 生成 NPM TOKEN

生成好了大概長這個樣子 1c14ee16-xxxx-4ae3-b09f-faca87axxxx (注:已做脫敏處理)

1.2 加入 GitHub 項(xiàng)目的 secrets 里

二、編寫 GitHub Actions 腳本

在你項(xiàng)目里創(chuàng)建 .github/workflows/main.yml 文件,內(nèi)容如下:

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 }}

完整內(nèi)容:https://github.com/Kennytian/tradex/blob/release/.github/workflows/main.yml

腳本解釋:

  • 兩個 release 表示向該分支 push 或提 PR 都會發(fā)布新的 NPM 版本
  • registry-url: https://registry.npmjs.org 表示 NPM 發(fā)布的目標(biāo)地址(現(xiàn)在可向 GitHub 發(fā) NPM 包)
  • npm publish || true 是不是特別熟悉,這其實(shí)是一條 Linux 命令,表示左邊的命令執(zhí)行失敗,就執(zhí)行后面的 true (這里有個坑,如果不加這個||,雖然能發(fā)布生成,但 Actions 一直會報(bào)錯,讓我很不解。如果您知道原因,請告之,錯誤詳情:https://github.com/Kennytian/tradex/runs/640232951?check_suite_focus=true
  • NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 表示 NPM 發(fā)布調(diào)用 TOKEN,這個 TOKEN 就是我們向 GitHub 里添加的secrets 值

三、額外知識點(diǎn)

最近在學(xué)習(xí) Linux,發(fā)現(xiàn)一個很好的視頻教程,現(xiàn)分享給大家:https://www.bilibili.com/video/BV1mW411i7Qf?p=68

文中運(yùn)用到的||,詳解如下:

全文完!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容