如何搭建npm私仓

3,069 阅读3分钟

公司有些资源是仅内部共享的,不能放到公有npm仓库里,这个时候搭建npm私仓进行内部管理很有必要。

1. 常用方案

常用的npm私仓搭建的成熟开源方案:

1.1 cnpm

cnpm是node.js库,国内Alibaba团队开发维护,提供私有的npm注册和同步服务。

1.2 Nexus

Nexus 是 Maven 仓库管理器,管理开发所需要的构件。本地架设 Maven 仓库服务器,代理远程仓库的同时维护本地仓库。

1.3 Verdaccio

Verdaccio 是一个 Node.js 创建的轻量的私有npm proxy registry。Verdaccio 开箱即用,拥有自己的小型数据库,能代理其他注册表(例如npmjs.org),缓存下载模块,且易于扩展。

2. Verdaccio工具搭建

这里介绍使用Verdaccio工具搭建私仓的过程。

2.1 安装Verdaccio

进入服务器目录,安装包文件:

npm install -g verdaccio

或者

yarn global add verdaccio

2.2 运行Verdaccio

包安装完成后,控制台输入:

verdaccio

image.png

2.3 修改配置文件

从2.2截图中读取配置文件目录,打开目录,修改配置文件config.yaml。

cd /home/xxx/.config/verdaccio/
vim config.yaml
i
uplinks:
  npmjs:
    url: https://registry.npmmirror.com/
  • 因为是部署在内网服务器上的,需要将配置文件中的ip地址更改为服务器内网ip地址。
listen: 172.26.14.133:4873 

i 切换为编辑模式。更改配置文件中的上行链路仓库地址为国内仓库地址;将 listen 地址修改为服务器地址。修改完后 esc 退出编辑,:wq! 保存修改。

最终 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", "crypt".
    # 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.npmmirror.com/

# 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: 172.26.14.133: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
logs: { 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;
#  }

# 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: en-US

通过ip地址访问: http://172.26.14.133:4873/

image.png

2.4 pm2启动Verdaccio

通过pm2守护进程启动Verdaccio。

npm install -g pm2
pm2 start verdaccio

image.png

status 为 online 表示启动成功。

提示:

如果需要重启verdaccio,则执行:

pm2 restart verdaccio

如果需要停止verdaccio,则执行:

pm2 stop verdaccio

2.5 发布包

git上准备好要发布的包文件。添加账号信息:

npm adduser --registry http://172.26.14.133:4873
Username: xiaowang
Password: 
Email: aa@163.com

账号添加完成后,发布包文件:

npm publish --registry http://172.26.14.133:4873

image.png

如果想删除包,可以执行以下命令:

npm unpublish xxx --force --registry http://172.26.14.133:4873 //清除发布的包

2.6 使用包

切换到使用包文件的git项目目录,拉取包文件。

npm install xxx --registry http://172.26.14.133:4873

或者

yarn add xxxx --registry http://172.26.14.133:4873

也可以在项目目录下新增 .npmrc 文件,指定仓库地址:

registry = http://172.26.14.133:4873

参考文档:

  1. 分分钟教会你搭建企业级的 npm 私有仓库
  2. 企业级npm仓库搭建
  3. 搭建自己的npm私有库
  4. verdaccio/verdaccio
  5. 搭建自己的私有npm库