私有npm库平台搭建

搭建私有npm源基于verdaccio, 简单方便

前期准备

  • npm(我搭建的时候用的Node版本是v14.21.3,npm版本是v6.14.18)
  • nvm (非必须, node版本管理, 可以切换node版本, 本文不做介绍)
  • nrm(非必须,但是有了这个会省事儿很多, 切换镜像源工具)
  • pm2(非必需,终端关闭后, 保持服务继续存活)

安装verdaccio

npm install -g verdaccio

启动verdaccio

verdaccio

出现下面说明成功

 info --- config file  - /Users/dabaoji/.config/verdaccio/config.yaml
 info --- the "crypt" algorithm is deprecated consider switch to "bcrypt" in the configuration file. Read the documentation for additional details
 info --- using htpasswd file: /Users/dabaoji/.config/verdaccio/htpasswd
 info --- plugin successfully loaded: verdaccio-htpasswd
 info --- plugin successfully loaded: verdaccio-audit
 warn --- http address - http://0.0.0.0:4873/ - verdaccio/5.26.3

访问地址http://localhost:4873 或者http://192.168.10.30:4873 出现下面页面, 其中192.168.10.30是机器的ip地址

image.png

启动后会在启动用户目录生成配置文件config.yaml
例如: /Users/dabaoji/.config/verdaccio/config.yaml

主要配置文件

  • config.yaml 启动后生成的是仓库的配置文件,仓库的配置都写在里面
  • htpasswd 当有用户注册后会生成的用户账号信息文件,记录账号和密码以及创建日期
  • storage 所有上传的包都保存在这

config.yaml配置项讲解

在配置前请一定注意配置文件内的缩进,不然会启动会报错
打开 config.yaml 配置文件,内容如下

#
# This is the default configuration file. It allows all users to do anything,
# please read carefully the documentation and best practices to
# improve security.
#
# Look here for more config file examples:
# https://github.com/verdaccio/verdaccio/tree/5.x/conf
#
# Read about the best practices
# https://verdaccio.org/docs/best

# path to a directory with all packages
storage: ./storage
# path to a directory with plugins to include
plugins: ./plugins

# https://verdaccio.org/docs/webui
web:
  title: Verdaccio
  # comment out to disable gravatar support
  # gravatar: false
  # by default packages are ordercer ascendant (asc|desc)
  # sort_packages: asc
  # convert your UI to the dark side
  # darkMode: true
  # html_cache: true
  # by default all features are displayed
  # login: true
  # showInfo: true
  # showSettings: true
  # In combination with darkMode you can force specific theme
  # showThemeSwitch: true
  # showFooter: true
  # showSearch: true
  # showRaw: true
  # showDownloadTarball: true
  #  HTML tags injected after manifest <scripts/>
  # scriptsBodyAfter:
  #    - '<script type="text/javascript" src="https://my.company.com/customJS.min.js"></script>'
  #  HTML tags injected before ends </head>
  #  metaScripts:
  #    - '<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>'
  #    - '<script type="text/javascript" src="https://browser.sentry-cdn.com/5.15.5/bundle.min.js"></script>'
  #    - '<meta name="robots" content="noindex" />'
  #  HTML tags injected first child at <body/>
  #  bodyBefore:
  #    - '<div id="myId">html before webpack scripts</div>'
  #  Public path for template manifest scripts (only manifest)
  #  publicPath: http://somedomain.org/

# https://verdaccio.org/docs/configuration#authentication
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
    # Hash algorithm, possible options are: "bcrypt", "md5", "sha1", "bcrypt".
    # algorithm: bcrypt # by default is crypt, but is recommended use bcrypt for new installations
    # Rounds number for "bcrypt", will be ignored for other algorithms.
    # rounds: 10

# https://verdaccio.org/docs/configuration#uplinks
# a list of other known repositories we can talk to
uplinks:
  npmjs:
    url: https://registry.npmjs.org/

# Learn how to protect your packages
# https://verdaccio.org/docs/protect-your-dependencies/
# https://verdaccio.org/docs/configuration#packages
packages:
  '@*/*':
    # scoped packages
    access: $all
    publish: $authenticated
    unpublish: $authenticated
    proxy: npmjs

  '**':
    # allow all users (including non-authenticated users) to read and
    # publish all packages
    #
    # you can specify usernames/groupnames (depending on your auth plugin)
    # and three keywords: "$all", "$anonymous", "$authenticated"
    access: $all

    # allow all known users to publish/publish packages
    # (anyone can register by default, remember?)
    publish: $authenticated
    unpublish: $authenticated

    # if package is not available locally, proxy requests to 'npmjs' registry
    proxy: npmjs

# To improve your security configuration and  avoid dependency confusion
# consider removing the proxy property for private packages
# https://verdaccio.org/docs/best#remove-proxy-to-increase-security-at-private-packages

# https://verdaccio.org/docs/configuration#server
# You can specify HTTP/1.1 server keep alive timeout in seconds for incoming connections.
# A value of 0 makes the http server behave similarly to Node.js versions prior to 8.0.0, which did not have a keep-alive timeout.
# WORKAROUND: Through given configuration you can workaround following issue https://github.com/verdaccio/verdaccio/issues/301. Set to 0 in case 60 is not enough.
server:
  keepAliveTimeout: 60
  # Allow `req.ip` to resolve properly when Verdaccio is behind a proxy or load-balancer
  # See: https://expressjs.com/en/guide/behind-proxies.html
  # trustProxy: '127.0.0.1'

# https://verdaccio.org/docs/configuration#offline-publish
# publish:
#   allow_offline: false

# https://verdaccio.org/docs/configuration#url-prefix
# url_prefix: /verdaccio/
# VERDACCIO_PUBLIC_URL='https://somedomain.org';
# url_prefix: '/my_prefix'
# // url -> https://somedomain.org/my_prefix/
# VERDACCIO_PUBLIC_URL='https://somedomain.org';
# url_prefix: '/'
# // url -> https://somedomain.org/
# VERDACCIO_PUBLIC_URL='https://somedomain.org/first_prefix';
# url_prefix: '/second_prefix'
# // url -> https://somedomain.org/second_prefix/'

# https://verdaccio.org/docs/configuration#security
# security:
#   api:
#     legacy: true
#     jwt:
#       sign:
#         expiresIn: 29d
#       verify:
#         someProp: [value]
#    web:
#      sign:
#        expiresIn: 1h # 1 hour by default
#      verify:
#         someProp: [value]

# https://verdaccio.org/docs/configuration#user-rate-limit
# userRateLimit:
#   windowMs: 50000
#   max: 1000

# https://verdaccio.org/docs/configuration#max-body-size
# max_body_size: 10mb

# https://verdaccio.org/docs/configuration#listen-port
# listen:
# - localhost:4873            # default value
# - http://localhost:4873     # same thing
# - 0.0.0.0:4873              # listen on all addresses (INADDR_ANY)
# - https://example.org:4873  # if you want to use https
# - "[::1]:4873"                # ipv6
# - unix:/tmp/verdaccio.sock    # unix socket

# The HTTPS configuration is useful if you do not consider use a HTTP Proxy
# https://verdaccio.org/docs/configuration#https
# https:
#   key: ./path/verdaccio-key.pem
#   cert: ./path/verdaccio-cert.pem
#   ca: ./path/verdaccio-csr.pem

# https://verdaccio.org/docs/configuration#proxy
# http_proxy: http://something.local/
# https_proxy: https://something.local/

# https://verdaccio.org/docs/configuration#notifications
# notify:
#   method: POST
#   headers: [{ "Content-Type": "application/json" }]
#   endpoint: https://usagge.hipchat.com/v2/room/3729485/notification?auth_token=mySecretToken
#   content: '{"color":"green","message":"New package published: * {{ name }}*","notify":true,"message_format":"text"}'

middlewares:
  audit:
    enabled: true

# https://verdaccio.org/docs/logger
# log settings
log: { type: stdout, format: pretty, level: http }
#experiments:
#  # support for npm token command
#  token: false
#  # disable writing body size to logs, read more on ticket 1912
#  bytesin_off: false
#  # enable tarball URL redirect for hosting tarball with a different server, the tarball_url_redirect can be a template string
#  tarball_url_redirect: 'https://mycdn.com/verdaccio/${packageName}/${filename}'
#  # the tarball_url_redirect can be a function, takes packageName and filename and returns the url, when working with a js configuration file
#  tarball_url_redirect(packageName, filename) {
#    const signedUrl = // generate a signed url
#    return signedUrl;
#  }
# 监听的端口,不配置这个,只能本机能访问, 一定要换行且加 -, 否则可能报错
listen:
  - 0.0.0.0:4873
# translate your registry, api i18n not available yet
# i18n:
# list of the available translations https://github.com/verdaccio/verdaccio/blob/master/packages/plugins/ui-theme/src/i18n/ABOUT_TRANSLATIONS.md
#   web: zh-CN

其实除去注释就是下面几项

  • storage 设置用户上传包的存放目录
  • plugins 插件目录
  • web 前端页面的配置,设置访问页的标题、图片等
  • i18n 设置页面的语言
    • web 设置web的默认语言 zh-CN
  • auth 设置账号相关的内容
    • file 存放账号密码的文件目录
    • max_user 最大注册用户,-1 代表禁止注册,但可以手动在账号文件添加
    • htpasswd 设置账号密码相关
  • uplinks 设置上游匹配,主要用于包匹配不到时,系统该往哪里去找这个包
  • packages 包相关配置,用于设置包的上传、下载、访问的权限控制
    • $all 所有登录、未登录者都可以访问
    • $authenticated 只有登录者可以访问
    • a、b、v等 指定用户名、只有该用户可以访问
    • access 可访问权,能否下载
    • publish 发布权
    • unpublish 取消发布权
    • 权限的控制大致有三种

下面提供一种简易的配置

# 设置保存放目录
storage: ./storage
plugins: ./plugins
web:   
  title: Npm
# 设置中文显示
i18n:   
  web: zh-CN
# 设置两个上游
uplinks:
  npmjs:
    url: https://registry.npmjs.org/
  cnpmjs:
    url: https://registry.npmmirror.com/
# 添加一项 @my/* 包的权限控制,只允许登录的用户可以下载上传
packages:
  '@my/*':
    access: $authenticated
    publish: $authenticated
    unpublish: $authenticated
  # 通配项,即上面配置不到的包都走这个
  '**':
    access: $all
    publish: $authenticated
    unpublish: $authenticated
    # 代理上游、如果本地找不到这个包应该去哪找,可以设置多个,按顺序查找
    proxy: cnpmjs npmjs
# 设置监听端口、以及支持IP访问
listen:   0.0.0.0:4873

创建用户(添加用户)

npm adduser --registry http://localhost:4873/

因为开始使用的node17, 版本不对, 添加用户一直报下面的错, 后来改成node14就可以了

npm notice Log in on http://localhost:4873/
npm ERR!  code ECONNREFUSED
npm ERR!  syscall connect
npm ERR!  errno ECONNREFUSED
npm ERR!  FetchError: request to http://localhost:4873/-/v1/login failed, reason: connect ECONNREFUSED ::1:4873
npm ERR!      at ClientRequest.<anonymous>  (/Users/dabaoji/.nvm/versions/node/v17.9.1/lib/node_modules/npm/node_modules/minipass-fetch/lib/index.js:130:14)
npm ERR!      at ClientRequest. emit (node:events:527:28)
npm ERR!      at Socket. socketErrorListener (node:_http_client:454:9)
npm ERR!      at Socket. emit (node:events:539:35)
npm ERR!      at emitErrorNT (node:internal/streams/destroy:164:8)
npm ERR!      at emitErrorCloseNT (node:internal/streams/destroy:129:3)
npm ERR!      at processTicksAndRejections (node:internal/process/task_queues:83:21)
npm ERR!   FetchError: request to http://localhost:4873/-/v1/login failed, reason: connect ECONNREFUSED ::1:4873
npm ERR!      at ClientRequest.<anonymous>  (/Users/dabaoji/.nvm/versions/node/v17.9.1/lib/node_modules/npm/node_modules/minipass-fetch/lib/index.js:130:14)
npm ERR!      at ClientRequest. emit (node:events:527:28)
npm ERR!      at Socket. socketErrorListener (node:_http_client:454:9)
npm ERR!      at Socket. emit (node:events:539:35)
npm ERR!      at emitErrorNT (node:internal/streams/destroy:164:8)
npm ERR!      at emitErrorCloseNT (node:internal/streams/destroy:129:3)
npm ERR!      at processTicksAndRejections (node:internal/process/task_queues:83:21) {
npm ERR!    code: 'ECONNREFUSED',
npm ERR!    errno: 'ECONNREFUSED',
npm ERR!    syscall: 'connect',
npm ERR!    address: '::1',
npm ERR!    port: 4873,
npm ERR!    type: 'system'
npm ERR!  }
npm ERR!
npm ERR!  If you are behind a proxy, please make sure that the
npm ERR!  'proxy' config is set properly.   See: 'npm help config'

npm ERR!  A complete log of this run can be found in:
npm ERR!      /Users/dabaoji/.npm/_logs/2023-10-09T02_23_14_574Z-debug-0.log

nrm 仓库管理工具(镜像管理工具)

使用nrm可以很方便的在不同源之间切换

安装

npm install -g nrm

新增

安装后我们可以通过nrm add [name] [address]这个命令来新增一个源地址, localhost也可以换成对应的ip地址如192.168.10.30

nrm add localnpm http://localhost:4873/

查看

使用nrm ls可以查看我们使用的所有源地址,带*是正在使用的地址;

  npm ---------- https://registry.npmjs.org/
  yarn --------- https://registry.yarnpkg.com/
  tencent ------ https://mirrors.cloud.tencent.com/npm/
  cnpm --------- https://r.cnpmjs.org/
* taobao ------- https://registry.npmmirror.com/
  npmMirror ---- https://skimdb.npmjs.com/registry/
  localnpm ----- http://localhost:4873/

切换

通过nrm use [name]来切换地址:

nrm use taobao
image.png

发布取消包

发布NPM包时一定要 nrm ls 查看是否选中了私有仓库源,否则将会发布到别的NPM仓库中(如果登录过的话)

这里我随便新建一个文件夹aa,通过npm init新建一个项目,然后在这个目录下


image.png

部署服务的本机发布

切换到对应的源
nrm use localnpm
登录私有仓库(登录才能发布, 否则报错)
npm login
Username: yao
Password:**
publish
npm publish

此时私有仓库就可以看到我们的包了

部署服务之外的其他机器发布

比如部署服务的ip地址为192.168.10.30

切换node版本

把node版本切换为部署服务机器node版本一致, 否则可能报以下错误

npm notice Log in on http://192.168.10.30:4873/
npm ERR! code ENYI
npm ERR! Web login not supported

起始这个报错和下面的一样, 就是node版本不正确

http fetch POST 404 http://192.168.10.30:4873/-/v1/login
添加源
nrm add privitenpm http://192.168.10.30:4873/
切换到对应的源
nrm use privitenpm
登录私有仓库
npm login
Username: yao
Password:**
publish
npm publish

取消发布

npm unpublish

使用

下载私有包

192.168.10.30就是私有仓库所在的ip地址

npm install xxx --registry http://192.168.10.30:4873
 # 或 
nrm use 私有源 
npm install xxx

注意:如果换成私有源后使用 npm install 下载非本地包,这时 proxy 代理上游就会起作用,系统会去代理上游选择包,直到最后一个代理。

注意上传时一定要注意源

守护进程启动

我们不能一直开着终端窗口, 但是关掉窗口, 服务就终止, 所以我们使用pm2启动verdaccio, 保持后台运行

安装pm2

npm install pm2 -g

启动verdaccio

pm2 start verdaccio

停止verdaccio

pm2 stop verdaccio

重启verdaccio

pm2 restart verdaccio

删除verdaccio

pm2 delete verdaccio

查看verdaccio

pm2 logs verdaccio

这里提出一点直接运行 pm2 start verdaccio 可能会启动失败,所以最后我们找到verdaccio的安装目录 进行全路径启动,这样就可以启动成功了,窗口关闭服务也不会停。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容