跳到主要內容
版本:9.x

動機

節省磁碟空間

An illustration of the pnpm content-addressable store. On the illustration there are two projects with node_modules. The files in the node_modules directories are hard links to the same files in the content-addressable store.

使用 npm 時,如果 100 個專案使用相依項,磁碟上將儲存 100 份該相依項的副本。使用 pnpm 時,相依項將儲存在內容可尋址的儲存區中,因此

  1. 如果您依賴相依項的不同版本,只有不同的檔案會新增至儲存區。例如,如果相依項有 100 個檔案,而新版本只有一個檔案變更,pnpm update 只會將 1 個新檔案新增至儲存區,而不是只為了單一變更而複製整個相依項。
  2. 所有檔案都儲存在磁碟上的單一位置。安裝套件時,其檔案會從該單一位置硬連結,不會消耗額外的磁碟空間。這允許您在專案間共用相同版本的相依性。

因此,您可以根據專案和相依性的數量節省大量磁碟空間,而且安裝速度會快很多!

提升安裝速度

pnpm 分三個階段執行安裝

  1. 相依性解析。識別所有需要的相依性並擷取到儲存區。
  2. 目錄結構計算。根據相依性計算 node_modules 目錄結構。
  3. 連結相依性。擷取所有剩餘的相依性,並從儲存區硬連結到 node_modules

An illustration of the pnpm install process. Packages are resolved, fetched, and hard linked as soon as possible.

此方法明顯比傳統的三階段安裝程序快,傳統程序會解析、擷取並將所有相依性寫入 node_modules

An illustration of how package managers like Yarn Classic or npm install dependencies.

建立非扁平的 node_modules 目錄

使用 npm 或 Yarn Classic 安裝相依性時,所有套件都會提升到模組目錄的根目錄。因此,原始碼可以存取未新增為專案相依性的相依性。

預設情況下,pnpm 使用符號連結,僅將專案的直接相依性新增到模組目錄的根目錄。

An illustration of a node_modules directory created by pnpm. Packages in the root node_modules are symlinks to directories inside the node_modules/.pnpm directory

如果您想要更詳細了解 pnpm 建立的獨特 node_modules 結構,以及為什麼它與 Node.js 生態系統配合良好,請閱讀

提示

如果您的工具無法與符號連結順利運作,您仍可以使用 pnpm,並將 node-linker 設定設為 hoisted。這會指示 pnpm 建立一個與 npm 和 Yarn Classic 建立的類似的 node_modules 目錄。