Node 項目通過 .npmrc 文件指定依賴安裝源

背景

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

(完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章