npm在沒有依賴的情況下,會將所有的依賴壓為一層,如下所示的依賴依賴關係

[email protected]@1.0.0

|[email protected]

某庫依賴於[email protected],和[email protected],但是[email protected]又依賴於[email protected],在這種沒有衝突的情況下,安裝後的結構如下:

[email protected]

|[email protected]

node_modules庫裡面只有[email protected]依賴和[email protected]依賴,

但是如果是在有衝突的情況下:

[email protected]@2.2.2

|[email protected]

庫依賴於[email protected],和[email protected],但是[email protected]又依賴於[email protected],這種情況下生成的依賴關係

[email protected]@2.2.2

|[email protected]

如果在一個項目中,這種情況很多,那麼整個項目的依賴關係將會非常的不幹凈,會產生很多的深層依賴,在實際中,有些組件的依賴並不是直接寫死了版本號,採用模糊版本號,如下:

~1.2.3 : >=1.2.3 <1.3.0

~1.2 : >=1.2.0 <2.0.0

~,就是最後一位版本號的所有範圍。

^1.2.3 : >=1.2.3 <2.0.0

^0.2.3 : >=0.2.3 <0.3.0^0.0.3 : >=0.0.3 <0.0.4

^ 就是小於非0最高位的那位數的+1 的所有範圍的,版本。

在上面的範圍內的多個版本,都只會下載一個版本,這樣就會發生版本衝突那些所有版本的衝突消失,只下載一個版本號。

但是還有一個問題就是,插件:比如我們發布了一個名字叫做webpack-plugin-a的插件,他只是webpack的一個插件,並不依賴webpack,所以不會把webpack寫入自身的dependencies或者devDependencies,但是它又確實需要針對特定的webpack版本來進行開發。

peer dependency:

Some way of saying, "I only work when plugged in to version 1.2.x of my host package, so if you install me, be sure that its alongside a compatible host." We call this relationship a peer dependency

設想以下場景:

1.我們開發[email protected]的時候是針對[email protected]來開發的

2.webpack發布了最新的[email protected]並且做了不兼容升級,導致[email protected]已經不能在該版本使用

3.有不明真相的開發者,安裝了[email protected]和我們的[email protected]

悲劇發生了,由於webpack版本不兼容,當該開發者執行編譯的時候肯定是要報錯的。那麼如何避免這種問題的發生呢?聰明的npm維護者們想到了使用peerDependencies來指定所需要兼容的宿主包的版本,我們在[email protected]package.json中添加如下配置:

"peerDependencies": {
"webpack": "^2.0.0"
}

這樣就指定了[email protected]只兼容[email protected],當用戶同時安裝[email protected][email protected]的時候就會拋出提示信息:

> UNMET PEER DEPENDENCY [email protected]
> npm WARN [email protected] requires a peer of webpack@^2.0.0 but none was installed

這樣讓開發者即使認識到未來會發生的錯誤,或者當前可能存在的風險。

並且官方文檔建議,在指定所需庫的版本號的時候,不應該是一個具體的版本號,更應該使用模糊版本號方式,這樣在插件開發的時候不會僅僅應為一個host pakage的版本號的一個改動就將插件運行失敗。

本文大部分內容都是來自以下倆篇文章:

npm的幾個坑

對peerDependencies的理解

Peer Dependencies


推薦閱讀:
相關文章