关于npm:如何使用Github-Actions发布npm包

3次阅读

共计 2300 个字符,预计需要花费 6 分钟才能阅读完成。

如何应用 Github Actions 公布 npm 包

作者:Herrylo

本文蕴含本地公布 npm 包公布流程,和 github action 主动公布 npm 包流程,帮忙你更好的公布本人或公司的 npm 包。

本地公布 npm 包

公布本地 npm 包首先须要初始化 npm,设置 npm 源,登录 npm,公布 npm

初始包

npm init

生成 package.json 包,如下是我的 package.json 配置:

{
  "name": "vuepress-plugin-md-tags", // 包名
  "version": "1.0.7", // 版本
  "description": "vuepress@1.x plugin", // 形容
  "main": "index.js", // 入口文件
  "scripts": {"test": "echo \"Error: no test specified\"&& exit 1"},
  "repository": { // 仓库
    "type": "git",
    "url": "https://github.com/HerryLo/vuepress-plugin-md-tags.git"
  },
  "keywords": ["vuepress@1.x", "vuepress-plugin", "tags"], // 关键字
  "author": "herrylo3", // 作者
  "license": "ISC", // license
  "bugs": {"url": "https://github.com/HerryLo/vuepress-plugin-md-tags/issues"},
  "homepage": "https://github.com/HerryLo/vuepress-plugin-md-tags"
}

设置 npm 源

npm config set registry https://registry.npmjs.org/
或者
nrm set npm

如果你公布包到 私有 npm 平台,设置 https://registry.npmjs.org/ 即可,如果是公有平台,记得设置公有 npm 源。

登录 npm

npm login

本地执行命令 npm login 进行登录,须要输出你的 npm 用户名、明码、邮箱地址,还有邮箱验证码,都搞完,才算是本地登录胜利。

公布包

在包目录下,本地执行命令执行命令 npm publish

npm publish

每次公布包时,记得批改 package.json 下的 vesion 版本号!

Github Action 公布 npm 包

首先你必定须要把代码上传到 Github 上,之后设置 Github Action 配置文件,在 npm 上生成 Granular Access Token,再在 Github Action 上设置 Actions secrets 字段。

::: tip
介绍以下内容时,默认你的代码以上传到 Github↓↓
:::

Github Action 配置文件

生成你本人我的项目的 Github Action 配置文件,Github 有提供模板,抉择图片中框出的模板即可

上面是我本人的配置文件

# 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://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages

name: Node.js Package

on:
  release:
    types: [created]
  push:
        #分支能够抉择多个,如:master、main、release
      #监听 main 分支的 push 操作,只有 main 分支产生 push 操作,即会运行公布代码
    branches:
      - main

jobs:
  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 install
      - run: npm publish
        env:
            # 通过 NPM_TOKEN,Github Action 才能够间接公布
          NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 

增加 npm token

生成 token 之后,马上复制,刷新之后就看不见了。之后将 token,设置到 github 我的项目 setting 中

记得点击 Add secret 按钮哦!

主动公布包

on:
  release:
    types: [created]
  push:
        #分支能够抉择多个,如:master、main、release
      #监听 main 分支的 push 操作,只有 main 分支产生 push 操作,即会运行公布代码
    branches:
      - main

设置的为每次 push 或 merge 会触发 github actions 主动公布包。当然,如何监听触发,你能够本人批改。

npm 包

npm 包:https://github.com/HerryLo/vuepress-plugin-md-tags

最近本人公布了 vuepress@1.x 插件 npm 包,如果你有应用 vuepress@1.x,能够看看。

::: tip
npm 包中的 README.md 文件,在上传到 npm 仓库之后,即是 npm 包首页,请大家正当编写 README.md,便于他人了解应用!
:::

完结

文章蛮简略,到这里就完结了,次要是对于 npm 包公布的流程步骤办法,心愿以上内容,能够帮忙到你。

正文完
 0