Node 项目通过 .npmrc 文件指定依赖安装源

本文详细介绍了如何使用npm命令及其配置文件.npmrc来指定依赖安装源和其他配置项。通过具体示例展示了如何设置不同的registry源以及如何使用npm配置命令进行管理和查看。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

npm 命令运行时,往往通过命令行指定相关配置,最常用的便是使用 --registry 来指定依赖的安装源。

npm install --registry=https://registry.npmmirror.com

同样的效果也可以使用 .npmrc 来实现:

registry=https://registry.npmmirror.com

.npmrc 用法介绍

.npmrc(NPM Running Configuration)可以指定 npm 命令运行时的配置内容,其中可以设置的配置见官方文档:config

配置优先级按顺序如下:

  1. 项目内的配置文件(/path/to/my/project/.npmrc
  2. 用户配置文件(~/.npmrc
  3. 全局配置文件($PREFIX/etc/npmrc
  4. NPM 内置配置文件(/path/to/npm/npmrc

.npmrc 文件内以键值对的形式(key=value)设置值:

key=value

数组:

key[]=value
key[]=value

使用 #; 来注释:

# Comment1
; Comment2
key=value

指定安装源

由于项目下的 .npmrc 优先级最高,并且配置文件只对此项目有效,不会影响其他项目。可以在项目根目录下面新建一个 .npmrc 文件指定安装源。

修改默认 registry

registry=https://registry.npmmirror.com

@scope 的依赖包从 https://scope.example.com 安装,其他从 https://registry.npmmirror.com

registry=https://registry.npmmirror.com
@scope:registry=https://scope.example.com

设置 SASS 镜像源,效果与 SASS_BINARY_SITE=https://registry.npmmirror.com/-/binary/node-sass npm install node-sass 相同:

sass_binary_site=https://registry.npmmirror.com/-/binary/node-sass

案例代码:https://github.com/mazeyqian/mazey/blob/master/.npmrc

NPM 配置快捷命令

获取当前配置指定值:

npm config get sass_binary_site
# https://registry.npmmirror.com/-/binary/node-sass

npm config get registry
# https://registry.npmmirror.com

设置配置指定值:

npm config set example_key_1 example_value_1
npm config get example_key_1
# example_value_1

显示配置列表:

npm config list

; userconfig
example_key_1 = "example_value_1"
registry = "https://registry.npmjs.org/"

注意

如果想发布 NPM,一定要注意修改 registry 至你想发布的地址,切勿将公司私有包发布到官方库中。

If you then want to publish a package for the whole world to see, you can simply override the --registry option for that publish command.

参考

  1. 淘宝 npm 域名即将切换 && npmmirror 重构升级
  2. Can I run my own private registry?
  3. 解决 NPM 安装 node-sass 因为网络问题超时失败的问题

版权声明

本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者后除和本文原始地址:https://blog.mazey.net/2950.html

(完)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值