Nexus如何搭建自己的npm库

432 阅读2分钟

步骤 1: 安装和运行 Nexus

  1. 下载 Nexus:

  2. 启动 Nexus:

    • 解压下载的文件,进入解压后的目录。

    • 启动 Nexus:

      bash
      复制代码
      ./nexus-<version>/bin/nexus.exe /run
      
    • 默认情况下,Nexus 会运行在 http://localhost:8081

  3. 访问 Nexus:

    • 打开浏览器,访问 http://localhost:8081
    • 使用默认的管理员用户名和密码登录(用户名为admin,默认密码在sonatype-work/nexus3/admin.password文件中)。

步骤 2: 创建 npm 仓库

  1. 登录 Nexus

    • 使用管理员账号登录 Nexus 管理界面。
  2. 创建 Hosted(私有)npm 仓库

    • 在左侧菜单中,选择 Repositories,然后点击 Create repository

    • 选择 npm (hosted) 作为仓库类型。

    • 填写仓库信息:

      • Name: 为你的 npm 仓库起一个名字,例如 npm-private
      • Version Policy: 通常选择 Mixed
      • Storage: 保持默认即可。
      • Deployment: 勾选 Allow redeploy(允许重新部署)。
    • 点击 Create repository 完成创建。

  3. 创建 Proxy(代理)npm 仓库(可选):

    • 用于代理 npm 官方仓库,可以创建一个 npm proxy。

    • 选择 npm (proxy) 作为仓库类型。

    • 填写仓库信息:

      • Name: 例如 npm-proxy
      • Remote Storage: 设置为 https://registry.npmjs.org/
    • 点击 Create repository 完成创建。

  4. 创建 Group(组合)npm 仓库(可选):

    • 组合 Hosted 和 Proxy 仓库,便于同时访问本地包和代理包。

    • 选择 npm (group) 作为仓库类型。

    • 填写仓库信息:

      • Name: 例如 npm-group
      • Member repositories: 添加之前创建的 npm-privatenpm-proxy
    • 点击 Create repository 完成创建。

步骤 3: 配置 npm 使用 Nexus 仓库

  1. 配置 npm 登录 Nexus:

    • 使用以下命令登录 Nexus npm 仓库:

      bash
      复制代码
      npm login --registry=http://localhost:8081/repository/npm-private/
      
    • 提供用户名、密码和邮箱地址(根据 Nexus 配置)。

  2. 设置 npm 的 .npmrc 文件

    • 配置 npm 使用 Nexus 仓库:

      bash
      复制代码
      npm set registry http://localhost:8081/repository/npm-private/
      
    • 如果你设置了 group 仓库,指向 group 仓库:

      bash
      复制代码
      npm set registry http://localhost:8081/repository/npm-group/
      

步骤 4: 发布和使用 npm 包

  1. 发布 npm 包

    • 使用以下命令将包发布到 Nexus 私有仓库:

      bash
      复制代码
      npm publish --registry=http://localhost:8081/repository/npm-private/
      
  2. 安装 npm 包

    • 在其他项目中使用以下命令安装包:

      bash
      复制代码
      npm install your-package-name --registry=http://localhost:8081/repository/npm-private/
      

通过以上步骤,你就可以成功搭建和使用自己的 npm 私有库在 Nexus 中了。确保访问和发布包时使用正确的仓库 URL,并根据需求设置相应的权限和角色管理。