likes
comments
collection
share

分享自己发布的第一个npm包流程

作者站长头像
站长
· 阅读数 12

作者: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平台,设置 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 字段。

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

Github Action配置文件

生成你自己项目的Github Action配置文件,Github有提供模板,选择图片中框出的模板即可

分享自己发布的第一个npm包流程

下面是我自己的配置文件

# 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

分享自己发布的第一个npm包流程

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

分享自己发布的第一个npm包流程

记得点击Add secret按钮哦!

自动发布包

以上添加成功之后,就可以使用github actions 自动发布npm包了。

on:
  release:
    types: [created]
  push:
    #分支可以选择多个,如:master、main、release
    #监听main分支的push操作,只要main分支发生push操作,即会运行发布代码
    branches:
      - main

由于,我是设置每次 push 或 merge, 会触发 github actions 自动发布包,所以每次push main分支,就会触发更新。

当然,如何监听触发,你可以自己修改。你可以手动触发一下,下面是成功的例子↓↓

分享自己发布的第一个npm包流程

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

npm包

npm包:github.com/HerryLo/vue…

最近自己发布了 vuepress@1.x 插件npm包,如果你有使用vuepress@1.x,可以看看。

提示: npm包中的README.md文件,在上传到npm仓库之后,即是npm包首页,请大家合理编写README.md,便于别人理解使用!

结束

文章蛮简单,到这里就结束了。文章主要是关于npm包发布的流程步骤方法,希望以上内容,可以帮助到你。