Глобальні пакунки
Глобальні пакунки — це інструменти та утиліти командного рядка, які встановлюються для всієї системи за допомогою команди pnpm add -g. В pnpm v11, управління лобальними пакунками було змінено для досягнення кращої ізоляції та надійності.
Втсановлення глобальних пакунків#
pnpm add -g <pkg>
Наприклад:
pnpm add -g typescript prettier eslint
обережно
Do not run these commands through sudo. pnpm keeps global packages and configuration in the invoking user's home directory, so under sudo they operate on the root user's home instead of yours. Since v11.21.0, pnpm setup, pnpm self-update, and every command that modifies the global installation print a warning when run as root. Read-only commands such as pnpm bin -g are unaffected.
Ізольоване встановлення#
Кожен глобально встановлений пакунок (або група пакунків, встановлених разом) отримує власну ізольовану теку зі своїми package.json, node_modules/ та файлом блокування. Це запобігає взаємному впливу глобальних пакунків через конфлікти залежностей між одноранговими компонентами, через підняття змін або зміни у визначенні версій.
Ізольовані встановлення зберігаються в {pnpmHomeDir}/global/v11/{hash}/, де hash формується від набору пакунків встановлених разом.
Наприклад, виконання цих команд:
pnpm add -g typescript
pnpm add -g prettier
creates two separate isolated installations. typescript and prettier each get their own node_modules tree and cannot affect each other's dependency resolution.
Installing multiple space-separated packages in a single command also creates a separate isolated install for each one:
pnpm add -g eslint prettier
eslint and prettier each get their own node_modules tree and lockfile and can be removed independently. pnpm remove -g eslint leaves prettier untouched.
To bundle multiple packages into the same isolated install (so they share a node_modules tree and lockfile, resolve peer dependencies against each other, and are removed together), pass them as a comma-separated list:
pnpm add -g eslint,prettier
Here eslint and prettier form a single install group. Removing either with pnpm remove -g removes the whole group.
pnpm add -g <pkg> replaces every existing group that contains <pkg>. After pnpm add -g eslint, the eslint,prettier group is gone, and so are prettier and its bins. To keep the group, add it again as a whole (pnpm add -g eslint,prettier), or use pnpm update -g.
The two forms can be mixed. Наприклад:
pnpm add -g eslint,prettier typescript
bundles eslint and prettier into one isolated install while installing typescript on its own.
Directory layout#
The contents of {pnpmHomeDir}/global/v11/ look like:
{pnpmHomeDir}/global/v11/
├── {hash-A} → symlink → ./{hash-A-target}/
├── {hash-A-target}/ ← isolated install dir
│ ├── package.json ← lists the packages installed together
│ ├── pnpm-lock.yaml ← lockfile for this install group
│ └── node_modules/
│ ├── <pkg>/ ← top-level dep, symlinked into the global virtual store
│ └── .pnpm/ ← the group's install state
├── {hash-B} → symlink → ./{hash-B-target}/
└── {hash-B-target}/ ← another isolated install dir
- The
{hash}entries are symlinks; pnpm scans for them to enumerate active installs. - The targets are real directories that act as ordinary pnpm projects. Each has its own
package.jsonand lockfile. - By default, the package contents live in the global virtual store at
{storeDir}/links, outside this directory. Each install group's direct dependencies (the entries at the root of itsnode_modules/) are symlinks into that store, so install groups that depend on the same package share one copy. WithvirtualStoreType: project, each install group keeps its packages in its ownnode_modules/.pnpm. - Bin shims live in
{pnpmHomeDir}/bin/and point through the appropriate install group'snode_modules.
When a package is removed or its install group is replaced, the hash symlink is updated. Orphaned target directories older than five minutes are removed at the start of the next pnpm add -g, pnpm update -g, or pnpm self-update.
Listing global packages#
pnpm list -g
pnpm list -g --json # machine-readable
pnpm list -g --parseable # paths only
Because each install group has its own lockfile, listing across multiple groups can only reliably aggregate the top-level packages they were installed with. Transitive dependency trees from different groups can't be coherently merged. As a result:
pnpm list -g(default--depth=0) always works and shows every globally installed package.pnpm list -g --depth=<n>(withn > 0) shows the full dependency tree only when:- there is just one global install group, or
- a positional argument narrows the request to a single install group, e.g.
pnpm list -g eslint --depth=1.
If --depth>0 is requested but the request can't be narrowed to a single install group, pnpm errors with ERR_PNPM_GLOBAL_LS_DEPTH_NOT_SUPPORTED.
Управління глобальними пакунками#
| Команда | Опис |
|---|---|
pnpm add -g <pkg> |
Встановлює пакунок глобально |
pnpm remove -g <pkg> |
Remove a globally installed package (if it was bundled into an install group, the whole group is removed) |
pnpm update -g [pkg] |
Update global packages (re-installs a package into a new isolated directory when its resolved dependency graph changed) |
pnpm list -g |
Виводить перелік глобально встановлених пакунків |
нотатка
Команда pnpm install -g (без аргументів) не підтримується. Використовуйте pnpm add -g <pkg> для встановлення потрібних паккунків.
Розташування бінарних файлів#
Глобально встановлені бінарні файли зберігаються у субтеці bin в PNPM_HOME (тобто в $PNPM_HOME/bin/). This keeps the PNPM_HOME directory clean. Internal directories like global/ and store/ don't pollute shell autocompletion when PNPM_HOME is on PATH.
Після оновлення до pnpm v11 виконайте pnpm setup для оновлення налаштувань вашої оболонки, щоб шлях $PNPM_HOME/bin був у вашому PATH.
Ви можете дізнатись шлях до глобальної теки bin наступним чином:
pnpm bin -g
Глобальне віртуальне сховище#
Глобальні встановлення використовуються глобальне віртуальне сховище. Пакунки зберігаються в {storeDir}/links та спільно використовуються поміж глобальними встановленнями. Це дозволяє уникнути зайвих завантажень, коли кілька глобальних пакунків залежать від одних і тих самих бібліотек.
Реєстрація локальних пакунків як глобальних#
Щоб зробити бінарні файли локального пакунка доступними для всієї системи, виконайте команду pnpm add -g . в теці вашого пакунка:
cd ~/projects/my-tool
pnpm add -g .
Виконання команти призведе до реєстрації компонентів теки bin пакунка для виклику з будь-якого місця у системі. Див. pnpm link для отримання додаткової інформації.
Ухваленя скриптів збірки#
Глобальні пакунки, що містять скрипти збірки (наприклад, postinstall), потребують ухвалення. Коли ви встановлюєте глобальний пакунок, який потребує запуску скриптів збірки, pnpm інтерактивно запропонує вам ухвалити або відхилити збірку.
Ви також можете попередньо ухвалити збірки, використовуючи прапорець --allow-build:
pnpm add -g --allow-build=esbuild esbuild
Since v11.24.0, pnpm approve-builds --global
lets you decide after the fact instead. It collects the packages awaiting approval from every
install group, asks about them once, and writes one allowBuilds policy into the
pnpm-workspace.yaml of the global packages directory, then rebuilds only the
groups that contain something you approved:
pnpm approve-builds -g