如何发布 npm 到 github pages?

发布 npm 到 github pages

github 可支持上传多种类型打包项目,且因 github 已收购npm,所以可以上传包括npm类型在内的各种 package。本文记录一下如何发布 npm 到 github pages。

打包

js 复制代码
# index.js
console.log("hello, world!")
bash 复制代码
npm init

npm init 命令会生成一个 package.josn 文件,例如:

json 复制代码
{
  "name": "@cyclonemind/package_exemple",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "exit 0"
  },
  "author": "",
  "license": "ISC",
  "description": "",
}

推送的 action

通过 github actions 实现 【发布一个 release 时将 npm 包推送到 githubpages 的服务器】的功能。我们建立 一个 release.yml 文件:

yaml 复制代码
# release.yml
name: Node.js Package

on:
   release:
    types: [created]

jobs:

    publish-gpr:

      runs-on: ubuntu-latest

      permissions:
        contents: read
        packages: write


      steps:
        - uses: actions/checkout@v4

        - uses: actions/setup-node@v4
          with:
            node-version: '16'
            registry-url: 'https://npm.pkg.github.com/' # 生成必要的 .npmrc 文件,配置认证信息设置环境变量,这个配置会影响后续所有的 npm 命令,包括:npm ci、npm publish

        - run: npm ci

        - run: npm publish 
 
          env:
            NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}

实际上 actions 中的虚拟机中生成的 .npmrc 文件里面类似于:

plaintext 复制代码
# .npmrc
//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}
registry=https://npm.pkg.github.com/
always-auth=true

这一步完成后在 package.josn 中增加 publishconfig的配置信息:

json 复制代码
# package.josn
{
  "name": "@cyclonemind/package_exemple",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "exit 0"
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "publishConfig": {"@cyclonemind:registry": "https://npm.pkg.github.com"},
}

随后创在 github 中创建一个 release, release.yml 文件就会执行。一个 package 就建立完成:

一般来说使用别人发布的包时都在 package.json 中写好

json 复制代码
{
  ...
  "dependencies": {
    "@cyclonemind/package_exemple": "1.0.0"
  },
  ...
}

正常情况下,这时使用 npm install 安装包只会去 npm 的官方仓库下载包或者用户自己设置的仓库下载包。我们可以在项目中增加 .npmrc 文件来设置项目的 仓库配置信息:

::: warning

这里说的项目不是这个包项目,而是其他任意一个需要使用这个包的项目!

:::

在其他项目的根目录下增加

plaintext 复制代码
# .npmrc
@cyclonemind:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=YOUR _authToken

这里的 _authToken 是使用者自己的,在 Settings -> Developer Settings -> Personal acess tokens -> Tokens(classic) -> Generate new token -> Generate new token(classic) -> 勾选上与 package 有关的选项即可得到_authToken>。

然后就可以就可以正常 npm install

相关推荐
前端市界5 小时前
用 React 手搓一个 3D 翻页书籍组件,呼吸海浪式翻页,交互体验带感!
前端·架构·github
happyprince5 小时前
2026年02月07日热门github项目
github
CoderJia程序员甲6 小时前
GitHub 热榜项目 - 日榜(2026-02-06)
人工智能·ai·大模型·github·ai教程
荔枝吻8 小时前
忘记服务器密码,在Xshell7中查看已保存密码
运维·服务器·github
tod11310 小时前
TCP全连接队列与tcpdump抓包
网络·网络协议·tcp/ip·github·tcpdump
Luck_ff081011 小时前
百度指数数据采集与可视化平台 BaiduIndexHunter
github·开源软件
阿里嘎多学长11 小时前
2026-02-03 GitHub 热点项目精选
开发语言·程序员·github·代码托管
子兮曰18 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
m0_694845571 天前
tinylisp 是什么?超轻量 Lisp 解释器编译与运行教程
服务器·开发语言·云计算·github·lisp
June`1 天前
muduo项目排查错误+测试
linux·c++·github·muduo网络库