跳到主要内容

动机

节省磁盘空间

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 只需要添加一个 新文件到存储中,而不会因为一个文件的修改而保存依赖包的 所有文件。
  2. 所有文件都保存在硬盘上的统一的位置。当安装软件包时, 其包含的所有文件都会硬链接自此位置,而不会占用 额外的硬盘空间。这让你可以在项目之间方便地共享相同版本的 依赖包。

最终结果就是以项目和依赖包的比例来看,你节省了大量的硬盘空间, 并且安装速度也大大提高了!

提升安装速度

pnpm perfoms installation in three stages:

  1. Dependency resolution. All required dependencies are identified and fetched to the store.
  2. Directory structure calculation. The node_modules directory structure is calculated based on the dependencies.
  3. Linking dependencies. 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.

Creating a non-flat node_modules directory

当使用 npm 或 Yarn Classic 安装依赖包时,所有软件包都将被提升到 node_modules 的 根目录下。其结果是,源码可以访问 本不属于当前项目所设定的依赖包。

默认情况下,pnpm 则是通过使用符号链接的方式仅将项目的直接依赖项添加到 node_modules 的根目录下。

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 生态系统中很好地工作的话,请阅读以下内容:

提示

如果你的工具不能很好地处理符号链接(symlinks),你仍然可以使用 pnpm,只需将 node-linker 设置为 hoisted 即可。这将告诉 pnpm 按照 npm 和 Yarn Classic 的方式创建一个 node_modules 目录。