动机
节省磁盘空间
🌐 Saving disk space
使用 npm 时,如果你有 100 个项目使用某个依赖,你将在磁盘上保存该依赖的 100 个副本。使用 pnpm 时,该依赖将存储在内容可寻址存储中,因此:
🌐 When using npm, if you have 100 projects using a dependency, you will have 100 copies of that dependency saved on disk. With pnpm, the dependency will be stored in a content-addressable store, so:
- 如果你依赖不同版本的依赖,只有不同的文件会被添加到存储中。例如,如果它有100个文件,而新版本只在其中一个文件上有更改,
pnpm update只会将该新文件添加到存储中,而不会为了单一的更改克隆整个依赖。 - 所有文件都保存在磁盘上的一个位置。当安装软件包时,它们的文件会从该位置创建硬链接,不会占用额外的磁盘空间。这使你能够在不同项目中共享相同版本的依赖。
因此,你可以根据项目和依赖的数量节省大量磁盘空间,并且安装速度更快!
🌐 As a result, you save a lot of space on your disk proportional to the number of projects and dependencies, and you have a lot faster installations!
提高安装速度
🌐 Boosting installation speed
pnpm 分三个阶段执行安装:
🌐 pnpm performs installation in three stages:
- 依赖解析。所有必需的依赖都已被识别并获取到存储中。
- 目录结构计算。
node_modules目录结构是根据依赖计算的。 - 正在链接依赖。所有剩余的依赖都已从存储中获取并硬链接到
node_modules。
这种方法比传统的三阶段安装流程(解析、获取和将所有依赖写入 node_modules)要快得多。
🌐 This approach is significantly faster than the traditional three-stage installation process of resolving, fetching, and writing all dependencies to node_modules.
创建非扁平 node_modules 目录
🌐 Creating a non-flat node_modules directory
使用 npm 或 Yarn Classic 安装依赖时,所有包都会被提升到模块目录的根目录。因此,源代码可以访问未被添加为项目依赖的依赖。
🌐 When installing dependencies with npm or Yarn Classic, all packages are hoisted to the root of the modules directory. As a result, source code has access to dependencies that are not added as dependencies to the project.
默认情况下,pnpm 使用符号链接仅将项目的直接依赖添加到模块目录的根目录中。
🌐 By default, pnpm uses symlinks to add only the direct dependencies of the project into the root of the modules directory.
如果你想了解更多关于 pnpm 创建的独特 node_modules 结构以及它为什么能很好地与 Node.js 生态系统兼容的详细信息,请阅读:
🌐 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:
如果你的工具对符号链接支持不佳,你仍然可以使用 pnpm,并将 nodeLinker 设置为 hoisted。这将指示 pnpm 创建一个类似于 npm 和 Yarn Classic 所创建的 node_modules 目录。
🌐 If your tooling doesn't work well with symlinks, you may still use pnpm and set the nodeLinker setting to hoisted. This will instruct pnpm to create a node_modules directory that is similar to those created by npm and Yarn Classic.