背景
npm
命令運行時,往往通過命令行指定相關配置,最常用的便是使用 --registry
來指定依賴的安裝源。
npm install --registry=https://registry.npmmirror.com
同樣的效果也可以使用 .npmrc
來實現:
registry=https://registry.npmmirror.com
.npmrc
用法介紹
.npmrc
(NPM Running Configuration)可以指定 npm
命令運行時的配置內容,其中可以設置的配置見官方文檔:config。
配置優先級按順序如下:
- 項目內的配置文件(
/path/to/my/project/.npmrc
) - 用戶配置文件(
~/.npmrc
) - 全局配置文件(
$PREFIX/etc/npmrc
) - 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 thatpublish
command.
參考
- 淘寶 npm 域名即將切換 && npmmirror 重構升級
- Can I run my own private registry?
- 解決 NPM 安裝 node-sass 因爲網絡問題超時失敗的問題
版權聲明
本博客所有的原創文章,作者皆保留版權。轉載必須包含本聲明,保持本文完整,並以超鏈接形式註明作者後除和本文原始地址:https://blog.mazey.net/2950.html
(完)