如何发布 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

相关推荐
徐小夕6 小时前
再也不怕看不懂 GitHub 代码!这款AI开源项目,一键生成交互架构图
前端·算法·github
一点一木9 小时前
🚀 2025 年 07 月 GitHub 十大热门项目排行榜 🔥
前端·人工智能·github
qianmoQ9 小时前
GitHub 趋势日报 (2025年07月28日)
github
一块plus11 小时前
1,000 万 DOT 奖励,JAM Prize 邀你共建 Polkadot 下一代基础设施!
javascript·后端·github
MicrosoftReactor15 小时前
技术速递|GitHub Copilot 的 Agent 模式现已全面上线 JetBrains、Eclipse 和 Xcode!
ai·github·copilot
qianmoQ1 天前
GitHub 趋势日报 (2025年07月27日)
github
SpiderPex1 天前
GitHub下载项目完整配置SSH步骤详解
运维·ssh·github
codervibe1 天前
从毕业设计到企业级模板:一次 Spring Boot 后端项目目录结构重构实录
后端·github
Github项目推荐1 天前
Rust生态系统在Web开发中的优势(9754)
面试·github
一念&1 天前
Git 与 GitHub 的对比与使用指南
git·github