跳到主内容
版本:9.x

项目初衷

节省磁盘空间

An illustration of the pnpm content-addressable store. 在插图中有两个带有 node_modules 的项目。 The files in the node_modules directories are hard links to the same files in the content-addressable store.

使用 npm 时,依赖每次被不同的项目使用,都会重复安装一次。  而在使用 pnpm 时,依赖会被存储在内容可寻址的存储中,所以:

  1. 如果你用到了某依赖项的不同版本,只会将不同版本间有差异的文件添加到仓库。 For instance, if it has 100 files, and a new version has a change in only one of those files, pnpm update will only add 1 new file to the store, instead of cloning the entire dependency just for the singular change.
  2. 所有文件都会存储在硬盘上的某一位置。 当软件包被被安装时,包里的文件会硬链接到这一位置,而不会占用额外的磁盘空间。 这允许你跨项目地共享同一版本的依赖。

因此,您在磁盘上节省了大量空间,这与项目和依赖项的数量成正比,并且安装速度要快得多!

提高安装速度

pnpm 分三个阶段执行安装:

  1. 依赖解析。 仓库中没有的依赖都被识别并获取到仓库。
  2. 目录结构计算。 The node_modules directory structure is calculated based on the dependencies.
  3. 链接依赖项。 All remaining dependencies are fetched and hard linked from the store to node_modules.

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

This approach is significantly faster than the traditional three-stage installation process of resolving, fetching, and writing all dependencies to 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

If you'd like more details about the unique node_modules structure that pnpm creates and why it works fine with the Node.js ecosystem, read:

提示

If your tooling doesn't work well with symlinks, you may still use pnpm and set the node-linker setting to hoisted. 这样 pnpm 就会创建一个类似于 npm 和 Yarn Classic 创建的 node_modules 目录。