部署 NPM 私有服务器
在 Windows 上部署 NPM 私有服务器有几种方法,以下是常见的几种方案:
方法一:使用 Verdaccio(推荐)
Verdaccio 是一个轻量级的私有 NPM 代理注册表,非常适合在 Windows 上运行。
安装步骤:
- 安装 Node.js
- 从Node.js 官网下载并安装 LTS 版本
- 全局安装 Verdaccio
cmd
npm install -g verdaccio
- 运行 Verdaccio
cmd
verdaccio
默认会启动在 http://localhost:4873
- 配置为 Windows 服务(可选)
- 使用
winser
将 Verdaccio 设为 Windows 服务:
cmd
npm install -g winser
cd %APPDATA%\npm\node_modules\verdaccio
winser -i
- 配置 NPM 客户端使用私有服务器
cmd
npm set registry http://localhost:4873
方法二:使用 Sinopia(已不维护)
Sinopia 是 Verdaccio 的前身,现已不推荐使用。
方法三:使用 Nexus Repository OSS
Sonatype Nexus 是一个功能更强大的制品库管理工具,支持 NPM、Maven 等多种格式。
安装步骤:
- 下载 Nexus
- 从Sonatype 官网下载 Windows 版本
- 安装并运行
- 解压后运行
nexus.exe /run
- 默认访问地址
http://localhost:8081
- 配置 NPM 仓库
- 登录后创建新的 NPM 代理仓库、宿主仓库和组仓库
方法四:使用 CNPM
CNPM 是淘宝 NPM 镜像的私有部署版本。
安装步骤:
- 安装 CNPM 服务器
cmd
npm install -g cnpmjs.org cnpm sqlite3
- 初始化配置
cmd
cnpmjs.org init
- 启动服务
cmd
cnpmjs.org start
配置说明
Verdaccio 配置文件(~/.config/verdaccio/config.yaml)
yaml
storage: ./storage
plugins: ./plugins
web:
title: My Private NPM
# comment out to disable gravatar support
# gravatar: false
auth:
htpasswd:
file: ./htpasswd
# Maximum amount of users allowed to register, defaults to "+inf".
# You can set this to -1 to disable registration.
# max_users: 1000
uplinks:
npmjs:
url: https://registry.npmjs.org/
packages:
'@*/*':
access: $all
publish: $authenticated
proxy: npmjs
'**':
access: $all
publish: $authenticated
proxy: npmjs
server:
keepAliveTimeout: 60
middlewares:
audit:
enabled: true
logs:
- {type: stdout, format: pretty, level: http}
#- {type: file, path: verdaccio.log, level: info}
使用私有 NPM 服务器
- 发布包到私有服务器
cmd
npm publish --registry http://localhost:4873
- 从私有服务器安装包
cmd
npm install my-private-package --registry http://localhost:4873
- 永久设置私有注册表
cmd
npm set registry http://localhost:4873
注意事项
- 性能:Windows 文件系统性能可能影响 NPM 服务器的响应速度
- 备份:定期备份存储目录(Verdaccio 默认在~/.config/verdaccio/storage)
- 安全:配置适当的访问控制和 HTTPS
- 存储:私有包会占用磁盘空间,注意监控
对于小型团队或个人使用,Verdaccio 是最简单易用的选择;对于企业级需求,Nexus 提供更全面的功能。