npm 包发布流程指南(使用细粒度访问令牌)
概述
本文档详细介绍如何使用细粒度访问令牌发布 npm 包到官方注册表(registry.npmjs.org)。
准备工作
1. 创建细粒度访问令牌
-
登录 npmjs.com
- 访问:www.npmjs.com
- 使用账户登录
-
进入令牌管理页面
- 点击右上角头像
- 选择 Access Tokens
-
创建新令牌
- 点击 Create new token
- 选择 Granular access token
-
配置令牌权限
- 权限类型: 选择 Read and Publish
- 包范围: 选择你的包(如
@agent-lite/codex) - 重要: 勾选 Bypass 2FA for automation
- 描述(可选): 添加令牌用途描述,如 "CI/CD 发布令牌"
- 有效期: 根据安全策略设置
-
生成令牌
- 点击 Create Token
- 重要: 立即复制生成的令牌(只显示一次)
配置本地环境
2. 设置 npm 认证
# 使用 npm config 命令设置令牌
npm config set //registry.npmjs.org/:_authToken=你的令牌
# 验证配置
npm whoami --registry=https://registry.npmjs.org/
发布流程
4. 打包包文件
# 生成 tarball 包文件(如果还没有)
npm pack
# 或者从现有文件发布
npm publish [包文件名].tgz --access=public
示例:
npm publish agent-lite-codex-0.93.2.tgz --access=public --registry=https://registry.npmjs.org/
验证发布结果
5. 检查包状态
# 方法 1:查看包信息
npm view @agent-lite/codex
# 方法 2:查看特定版本
npm view @agent-lite/codex version
# 方法 3:查看所有版本
npm view @agent-lite/codex versions
# 方法 4:查看完整信息
npm info @agent-lite/codex
7. 网页验证
直接访问包页面:
https://www.npmjs.com/package/@agent-lite/codex
故障排除
常见错误及解决方案
错误 1: 403 Forbidden
npm error 403 403 Forbidden - PUT https://registry.npmjs.org/@agent-lite%2fcodex
解决方案:
- 确认令牌有 Publish 权限
- 确认已启用 Bypass 2FA
- 重新配置令牌:
npm config set //registry.npmjs.org/:_authToken=新令牌
错误 2: 404 Not Found
npm error 404 '@agent-lite/codex@*' is not in this registry
解决方案:
- 等待 5-10 分钟(npm 同步延迟)
- 使用网页验证包是否存在
- 重新发布
错误 3: Access token expired
npm notice Access token expired or revoked
解决方案:
- 创建新的访问令牌
- 更新本地配置
- 清除缓存:
npm cache clean --force
快速参考命令
# 1. 设置令牌
npm config set //registry.npmjs.org/:_authToken=npm_xxxxxxxxxxxx
# 2. 验证登录
npm whoami
# 3. 打包(如果需要)
npm pack
# 4. 发布
npm publish [包文件].tgz --access=public
# 5. 验证
npm view @你的/包名
支持资源
- 官方文档: docs.npmjs.com/
- 令牌管理: www.npmjs.com/settings/to…
- 发布指南: docs.npmjs.com/packages-an…
- 安全最佳实践: docs.npmjs.com/about-regis…
注意: npm 发布后可能需要几分钟同步时间。如果立即验证返回 404,请稍后再试。