GitHub——自动发布NPM包

2024-08-15 14:44:54 浏览数 (1)

前言

原理很简单,就是利用github的actions去触发上传到npm平台;

内容

?> 主要分为两个步骤: 1. 在NPM平台生成token 2. github配置secrets/actions

NPM生成token

登录npm平台, 生成一个token;

2022-08-31T22:39:47.png2022-08-31T22:39:47.png

GitHub配置secrets

登录Github平台, 配置secrets, 增加一个环境变量;

GitHub配置actions

?> 请根据自身项目的实际情况做出配置 | 建议先创建nodejs脚本用于测试, 测试通过后再创建正式的发包脚本。

测试脚本

!> 1. 我的代码没有测试脚本所以直接把npm test干掉了; 2. 打包的时候使用的是自定义脚本(build.sh),所以这里将脚本替换成了自己项目下的打包脚本; 3. 如果项目是用自己定义的脚本打包整个项目, 一定要记得赋予脚本执行的权限;

代码语言:javascript复制
git update-index --chmod= x build.sh
代码语言:javascript复制
# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions

name: cnblogs-theme-npm

on:
  push:
    branches: [ "v2" ]
  pull_request:
    branches: [ "v2" ]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [16.x]
        # See supported Node.js release schedule at https://nodejs.org/en/about/releases/

    steps:
    - uses: actions/checkout@v3
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v3
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'
    - run: npm ci
    - run: ./build.sh

发包脚本

?> 当建立release版本后,就会触发脚本进行发包;

代码语言:javascript复制
# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages

name: NPM-PUBLISH

on:
  release:
    types: [created]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 16
      - run: npm ci
      - run: ./build.sh

  publish-npm:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 16
          registry-url: https://registry.npmjs.org/
      - run: npm ci
      - run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{secrets.NPM_PUBLISH}}

0 人点赞