如何配置.npmrc实现作用域包部分模块从npm拉取、其余从GitHub Packages拉取?
好问题!其实你踩了npm配置的一个小坑——npm目前不支持为单个作用域子模块(比如@custompackage/module1)单独设置registry。你之前尝试的@custompackage/module1:registry这种语法是无效的,npm只会识别全局registry或者整个作用域级别的registry配置,所以才会继续去GitHub Packages找这个模块。
不过没关系,有两种靠谱的办法能实现你的需求:
办法一:安装时临时指定registry(简单直接)
每次安装或更新@custompackage/module1时,通过--registry参数强制指定从npm拉取:
npm install @custompackage/module1 --registry=https://registry.npmjs.org/
安装完成后,后续常规的npm install会使用本地缓存;如果要更新这个模块,同样需要加上该参数来从npm获取最新版本。
办法二:在package.json中持久化指定源(更省心)
如果你希望不需要每次手动加参数,能长期生效,可以在package.json的dependencies里给@custompackage/module1加上npm:前缀,强制它使用全局默认的npm registry:
{ "dependencies": { "@custompackage/module1": "npm:@custompackage/module1@^1.0.0", "@custompackage/other-module": "^2.0.0" } }
这个npm:前缀会让npm忽略作用域级别的registry配置,直接从你全局设置的https://registry.npmjs.org/拉取该模块;而@custompackage/other-module这类其他模块,依然会遵循@custompackage:registry的配置,从GitHub Packages拉取。
配置完成后,执行npm install就能自动分源拉取了,你可以查看package-lock.json里的resolved字段,确认@custompackage/module1的源是npm registry地址。
内容的提问来源于stack exchange,提问作者Vardan




