当前位置: 首页>后端>正文

私有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地址

私有npm库平台搭建,第1张

启动后会在启动用户目录生成配置文件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
私有npm库平台搭建,第2张

发布取消包

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

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


私有npm库平台搭建,第3张

部署服务的本机发布

切换到对应的源
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的安装目录 进行全路径启动,这样就可以启动成功了,窗口关闭服务也不会停。


https://www.xamrdz.com/backend/3dg1941830.html

相关文章: