如何在 .npmrc 中为范围注册表设置 _auth?

How to set _auth for a scoped registry in .npmrc?

我想知道如何配置 .npmrc 文件,以便我可以拥有一个默认注册表和一个具有身份验证功能的不同范围的注册表。

我将 Nexus 用于私有存储库,我不确定如何为范围注册表设置身份验证,只有默认注册表。

例如我的 ~/.npmrc 文件是:

registry=https://registry.npmjs.org/
@test-scope:registry=http://nexus:8081/nexus/content/repositories/npm-test/
email=test@user.com
_auth="…"

如果我对范围为 test-scope 的包执行 npm publish,我会收到身份验证错误。

AFAIK,_auth 仅适用于 registry=... 部分。有没有办法为 @test-scope:registry=... 部分指定授权密钥?

谢谢,

因此,在深入研究 NPM 源代码后,发现有一种方法可以做到这一点。

我的解决方案如下:

registry=https://registry.npmjs.org/
@test-scope:registry=http://nexus:8081/nexus/content/repositories/npm-test/
//nexus:8081/nexus/content/repositories/npm-test/:username=admin
//nexus:8081/nexus/content/repositories/npm-test/:_password=YWRtaW4xMjM=
email=…

解释:

范围 @test-scope 指定在执行 npm publish 命令时,具有范围的包应发布到与默认 registry= 不同的注册表。

//nexus:8081/... 开头的两行用于为 username_password 指定范围存储库的凭据,其中 _password 是 base64 编码的密码组件来自之前使用的 _auth 凭据。

使用这种方法,只会从私有注册表发布和安装范围内的包,所有其他包将从默认注册表安装。

编辑:

除此之外,密码可以指定为环境变量,这样它就不会以明文形式存储在文件中。

例如:

registry=https://registry.npmjs.org/
@test-scope:registry=http://nexus:8081/nexus/content/repositories/npm-test/
//nexus:8081/nexus/content/repositories/npm-test/:username=admin
//nexus:8081/nexus/content/repositories/npm-test/:_password=${BASE64_PASSWORD}
email=…

此外,使用 Nexus 时,必须指定 email= 行。

出于某些奇怪的原因,当与范围包一起使用时,_auth 被称为 _authToken。如果您正在使用它,则不必将纯文本密码存储在 .npmrc

registry=https://registry.npmjs.org/
@test-scope:registry=http://nexus:8081/nexus/content/repositories/npm-test/ 
//nexus:8081/nexus/content/repositories/npm-test/:_authToken=...
email=…

运行 以下命令,将 @company-scope 替换为范围,并 company-registry 使用贵公司的 npm Enterprise 注册中心的名称:

npm login --scope=@company-scope --registry=https://registry.company-registry.npme.io/

此信息可在 npm documention.

上找到