Перейти к основному содержимому
Версия: Next

Часто задаваемые вопросы

Почему моя папка node_modules использует дисковое пространство, если пакеты хранятся в глобальном хранилище?

pnpm создает hard links из глобального хранилища на папки проекта node_modules . Жесткие ссылки указывают на то же место на диске, где находятся исходные файлы. Так, например, если у вас есть foo в вашем проекте в качестве зависимости и он занимает 1 МБ места, то это будет выглядеть так, как будто он занимает 1 МБ места в папке проекта node_modules и столько же места в глобальном хранилище. However, that 1MB is the same space on the disk addressed from two different locations. Таким образом, всего foo занимает 1 МБ, а не 2 МБ.

Больше по этой теме:

Работает ли в Windows?

Короткий ответ: Да. Длинный ответ: использование символических ссылок в Windows, по меньшей мере, проблематично, но у есть обходной путь. Для Windows вместо этого мы используем точки соединения (junctions).

Но многоуровневое строение node_modules несовместимо с Windows?

В ранних версиях npm были проблемы из-за вложенности всех node_modules (см. это issue). Однако pnpm не создает глубоких папок, он хранит все пакеты без изменений и использует символические ссылки для создания древовидной структуры зависимостей.

А как насчет зацикленных символических ссылок?

Although pnpm uses linking to put dependencies into node_modules folders, circular symlinks are avoided because parent packages are placed into the same node_modules folder in which their dependencies are. So foo's dependencies are not in foo/node_modules, but foo is in node_modules together with its own dependencies.

Зачем вообще нужны жесткие ссылки? Почему бы не делать символические ссылки непосредственно к глобальному хранилищу?

Один пакет может иметь разные наборы зависимостей на одной машине.

In project A foo@1.0.0 can have a dependency resolved to bar@1.0.0, but in project B the same dependency of foo might resolve to bar@1.1.0; so, pnpm hard links foo@1.0.0 to every project where it is used, in order to create different sets of dependencies for it.

Direct symlinking to the global store would work with Node's --preserve-symlinks flag, however, that approach comes with a plethora of its own issues, so we decided to stick with hard links. For more details about why this decision was made, see this issue.

Работает ли pnpm на нескольких дисках или файловых системах?

The package store should be on the same drive and filesystem as installations, otherwise packages will be copied, not linked. This is due to a limitation in how hard linking works, in that a file on one filesystem cannot address a location in another. See Issue #712 for more details.

pnpm functions differently in the 2 cases below:

Указан путь к хранилищу

If the store path is specified via the store config, then copying occurs between the store and any projects that are on a different disk.

If you run pnpm install on disk A, then the pnpm store must be on disk A. If the pnpm store is located on disk B, then all required packages will be directly copied to the project location instead of being linked. This severely inhibits the storage and performance benefits of pnpm.

Store path is NOT specified

If the store path is not set, then multiple stores are created (one per drive or filesystem).

If installation is run on disk A, the store will be created on A .pnpm-store under the filesystem root. If later the installation is run on disk B, an independent store will be created on B at .pnpm-store. The projects would still maintain the benefits of pnpm, but each drive may have redundant packages.

Что означает название pnpm?

pnpm stands for performant npm. @rstacruz came up with the name.

pnpm does not work with <YOUR-PROJECT-HERE>?

In most cases it means that one of the dependencies require packages not declared in package.json. It is a common mistake caused by flat node_modules. If this happens, this is an error in the dependency and the dependency should be fixed. That might take time though, so pnpm supports workarounds to make the buggy packages work.

Решение 1

In case there are issues, you can use the node-linker=hoisted setting. This creates a flat node_modules structure similar to the one created by npm.

Решение 2

In the following example, a dependency does not have the iterall module in its own list of deps.

The easiest solution to resolve missing dependencies of the buggy packages is to add iterall as a dependency to our project's package.json.

You can do so, by installing it via pnpm add iterall, and will be automatically added to your project's package.json.

  "dependencies": {
...
"iterall": "^1.2.2",
...
}

Решение 3

One of the solutions is to use hooks for adding the missing dependencies to the package's package.json.

An example was Webpack Dashboard which wasn't working with pnpm. It has since been resolved such that it works with pnpm now.

It used to throw an error:

Error: Cannot find module 'babel-traverse'
at /node_modules/inspectpack@2.2.3/node_modules/inspectpack/lib/actions/parse

The problem was that babel-traverse was used in inspectpack which was used by webpack-dashboard, but babel-traverse wasn't specified in inspectpack's package.json. It still worked with npm and yarn because they create flat node_modules.

The solution was to create a .pnpmfile.cjs with the following contents:

module.exports = {
hooks: {
readPackage: (pkg) => {
if (pkg.name === "inspectpack") {
pkg.dependencies['babel-traverse'] = '^6.26.0';
}
return pkg;
}
}
};

After creating a .pnpmfile.cjs, delete pnpm-lock.yaml only - there is no need to delete node_modules, as pnpm hooks only affect module resolution. Then, rebuild the dependencies & it should be working.