美文网首页npmnpm
用 GitHub Actions 实现自动发布 NPM 包

用 GitHub Actions 实现自动发布 NPM 包

作者: Kenny锅 | 来源:发表于2020-05-03 18:59 被阅读0次

一、前置条件

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

      - 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

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

全文完!

相关文章

网友评论

    本文标题:用 GitHub Actions 实现自动发布 NPM 包

    本文链接:https://www.haomeiwen.com/subject/twcjghtx.html