@your-company:registry 和 registry 的区别
1. 作用范围不同
registry - 默认注册表
- 作用 : 设置所有包的默认下载源
- 影响范围: 全局,对所有 npm 包生效
- 使用场景: 公共包和没有特定作用域的包
ini
# 所有包都从这个地址下载
registry=https://registry.npmjs.org/
@your-company:registry - 作用域注册表
- 作用 : 只对特定作用域的包生效
- 影响范围 : 仅限于
@your-company开头的包 - 使用场景: 企业内部私有包
ini
# 只有 @your-company 开头的包从这个地址下载
@your-company:registry=http://nexus.company.com/repository/npm-private/
2. 实际使用示例
项目结构示例
my-project/
├── package.json
├── .npmrc
└── src/
package.json 示例
json
{
"name": "my-project",
"dependencies": {
"lodash": "^4.17.21", // 公共包 - 使用默认 registry
"react": "^18.0.0", // 公共包 - 使用默认 registry
"@your-company/ui-components": "^1.2.0", // 私有包 - 使用作用域 registry
"@your-company/utils": "^2.1.0" // 私有包 - 使用作用域 registry
}
}
.npmrc 配置示例
ini
# 默认注册表 - 用于公共包
registry=https://registry.npmjs.org/
# 作用域注册表 - 用于公司私有包
@your-company:registry=http://nexus.company.com/repository/npm-private/
# 另一个公司的作用域
@other-company:registry=http://nexus.other-company.com/repository/npm/
3. 下载时的行为差异
bash
# lodash 从 https://registry.npmjs.org/ 下载
npm install lodash
# react 从 https://registry.npmjs.org/ 下载
npm install react
# @your-company/ui-components 从 http://nexus.company.com/repository/npm-private/ 下载
npm install @your-company/ui-components
# @other-company/shared-lib 从 http://nexus.other-company.com/repository/npm/ 下载
npm install @other-company/shared-lib
4. 在 Nexus 环境中的典型配置
完整的 .npmrc 配置
ini
# 默认使用 Nexus 聚合仓库(包含公共包和私有包)
registry=http://nexus.company.com:8081/repository/npm-group/
# 公司私有包使用 hosted 仓库
@your-company:registry=http://nexus.company.com:8081/repository/npm-hosted/
# 如果需要,为其他公司配置
@partner-company:registry=http://nexus.partner.com/repository/npm/
# 认证信息(如果需要)
//nexus.company.com:8081/repository/npm-hosted/:_auth="YOUR_AUTH_TOKEN"
always-auth=true
5. 多作用域配置示例
ini
# 默认注册表
registry=https://registry.npmjs.org/
# 不同团队/项目使用不同的私有仓库
@company-team-a:registry=http://nexus.company.com/repository/team-a-npm/
@company-team-b:registry=http://nexus.company.com/repository/team-b-npm/
@company-shared:registry=http://nexus.company.com/repository/shared-npm/
# 合作伙伴的包
@partner-org:registry=https://npm.partner-org.com/
6. 发布时的区别
发布公共包
bash
# 使用默认 registry
npm publish
发布作用域包
bash
# 发布到 @your-company 配置的 registry
npm publish --registry=http://nexus.company.com/repository/npm-private/
# 或者直接发布,npm 会自动使用作用域配置的 registry
npm publish
7. 优先级规则
当同时配置了多个 registry 时,npm 按以下优先级解析:
- 作用域 registry (
@scope:registry) - 最高优先级 - 项目级 .npmrc 配置
- 用户级 .npmrc 配置
- 全局 npm config
- npm 默认 registry - 最低优先级
8. 实际场景建议
开发环境配置
ini
# 开发环境 .npmrc
registry=http://nexus-dev.company.com/repository/npm-group/
@your-company:registry=http://nexus-dev.company.com/repository/npm-hosted/
生产环境配置
ini
# 生产环境 .npmrc
registry=http://nexus-prod.company.com/repository/npm-group/
@your-company:registry=http://nexus-prod.company.com/repository/npm-hosted/
总结
registry: 设置所有包的默认下载源@your-company:registry: 只设置特定作用域包的下载源- 使用场景: 公共包走默认 registry,私有包走作用域 registry
- 优势: 实现公私包分离,提高下载效率和安全管控
这种配置方式既保证了公共包的正常下载,又确保了私有包的安全性和私密性。