Dependency Resolution Settings
overrides
Це поле дозволяє наказати pnpm замінити будь-яку залежність у графі залежностей, включаючи прямі залежності. Це корисно для того, щоб змусити всі ваші пакунки використовувати одну версію залежності, перенести виправлення, замінити залежність форком або видалити невикористовувану залежність.
Зверніть увагу, що поле перевизначень можна встановити лише у корені проєкту.
Приклад поля overrides:
overrides:
"foo": "^1.0.0"
"quux": "npm:@myorg/quux@^1.0.0"
"bar@^2.1.0": "3.0.0"
"qar@1>zoo": "2"
Ви можете вказати пакунок, до якого належить перевизначена залежність, відокремивши селектор пакунка від селектора залежності символом ">", наприклад, qar@1>zoo перевизначить лише залежність zoo пакунка qar@1, а не будь-які інші залежності.
To keep an overridden version in sync with the version used elsewhere in your workspace, define the version in a catalog and reference it with the catalog: protocol. This way the version is maintained in a single place and referenced from both your dependencies and your overrides:
catalog:
foo: "^1.0.0"
overrides:
foo: "catalog:"
You may also reference a named catalog with catalog:<name>. See Catalogs for more details.
Якщо ви вважаєте, що використання певного пакунка не потребує однієї з його залежностей, ви можете використовувати -, щоб вилучити її. Наприклад, якщо пакунок foo@1.0.0 потребує великого пакунка з назвою bar для функції, яку ви не використовуєте, вилучення цього пакунка може скоротити час встановлення:
overrides:
"foo@1.0.0>bar": "-"
Ця можливість особливо корисна для optionalDependencies, де більшість необовʼязкових пакунків можна безпечно пропустити.
Convergence overrides
Додано у: v11.13.0
A selector with an empty range — "pkg@" — is a convergence override. Unlike a regular override, which rewrites every matching edge unconditionally, a convergence override rewrites a dependency edge only when its version satisfies the range that edge declares:
overrides:
"form-data@": 4.0.6
With the above, a dependency that declares form-data: "^4.0.5" is pinned to 4.0.6, while one that declares ^3.0.0 keeps its own resolution. This lets compatible consumers converge on a single version — now and for any dependent added in the future — without forcing an incompatible version on the rest of the graph.
Rules:
- The value must be an exact version. A range, a dist-tag, or a
-removal fails withERR_PNPM_INVALID_CONVERGENCE_OVERRIDE. Acatalog:reference is allowed as long as the catalog entry resolves to an exact version. - Only plain semver edges participate. Edges declared with
workspace:,catalog:,npm:, a dist-tag, or a git/URL specifier have no meaningful "satisfies" relation and are left untouched. - Convergence overrides cannot be combined with a parent selector:
"parent>pkg@"is rejected. - A regular override always wins over a convergence override for the same edge.
When a full resolution finds that every declared range also admits a newer version, pnpm warns that the override is stale and names the version to converge on instead.
Before v11.13.0, an empty range in an override selector was undocumented and behaved like a bare (unscoped) override.
Перевизначення прямих залежностей
Перевизначення також застосовуються до peerDependencies. Поведінка залежить від типу специфікатора версії, що використовується в перевизначенні:
- Діапазони Semver (наприклад,
^1.0.0), протоколи workspace та catalog: прямі залеженості перевизначаються та залишаються прямими залежностями. - Специфікатори, що не визначають діапазон, такі як протоколи
link:абоfile:: прямі залежності замінюються та переміщується до розділуdependencies, оскільки ці специфікатори не є допустимими діапазонами для прямих залежностей. - Видалення (
-): прямі залежності повністю видаляється.
Наприклад, щоб перевизначити пряму залежність react для react-dom:
overrides:
"react-dom>react": "18.1.0"
packageExtensions
Поля packageExtensions надають можливість розширити наявні визначення пакунків додатковою інформацією. Наприклад, якщо react-redux повинен мати react-dom у своїх peerDependencies, але не має, можна виправити react-redux за допомогою packageExtensions:
packageExtensions:
react-redux:
peerDependencies:
react-dom: "*"
Ключами у packageExtensions є назви пакунків або назви пакунків і діапазони semver, тому можна виправити лише деякі версії пакунків:
packageExtensions:
react-redux@1:
peerDependencies:
react-dom: "*"
Наступні поля можна розширити за допомогою packageExtensions: dependencies, optionalDependencies, peerDependencies і peerDependenciesMeta.
Більший приклад:
packageExtensions:
express@1:
optionalDependencies:
typescript: "2"
fork-ts-checker-webpack-plugin:
dependencies:
"@babel/core": "1"
peerDependencies:
eslint: ">= 6"
peerDependenciesMeta:
eslint:
optional: true
Разом з Yarn ми підтримуємо базу даних packageExtensions для виправлення несправних пакунків в екосистемі.
Якщо ви використовуєте packageExtensions, подумайте про те, щоб надіслати PR і внести ваше розширення до бази даних @yarnpkg/extensions.
allowedDeprecatedVersions
Цей параметр дозволяє вимкнути попередження про застарілість певних пакунків.
Приклад:
allowedDeprecatedVersions:
express: "1"
request: "*"
У наведеній вище конфігурації pnpm не виводитиме попередження про застарілість для будь-якої версії request і для v1 express.
update
Додано у: v11.16.0
Settings in this section tune the pnpm update and pnpm outdated commands.
update.ignoreDeps
Іноді ви не можете оновити залежність. Наприклад, остання версія залежності почала використовувати ESM, але ваш проєкт ще не в ESM. На жаль, такий пакунок завжди буде виведено командою pnpm outdated і оновлено при виконанні pnpm update --latest. However, you may list packages that you don't want to upgrade in the ignoreDeps field:
update:
ignoreDeps:
- load-json-file
Також підтримуються шаблони, тому ви можете ігнорувати будь-які пакунки з області видимості: @babel/*.
update.changeset
Додано у: v11.16.0
- Стандартно: false
- Тип: Boolean
When true, pnpm update writes a change intent after updating workspace manifests, declaring a patch bump for every workspace package whose dependencies or optionalDependencies were changed by the update and a major bump when its peerDependencies changed. Same as passing --changeset; pass --no-changeset to override the setting for a single run.
update.githubActions
Додано у: v11.16.0
- Стандартно: false
- Тип: Boolean
When true, pnpm update and pnpm outdated also check the GitHub Actions referenced by the repository's workflow files. Same as passing --include-github-actions. See Updating GitHub Actions.
update.githubActionsServer
Added in: v11.17.0
- Default: the
GITHUB_SERVER_URLenvironment variable, falling back to https://github.com - Тип: URL
The base URL of the GitHub server that hosts the repositories of the GitHub Actions referenced by the workflow files (for example, a GitHub Enterprise Server). The URL must use the https:// or http:// protocol. Only use http:// for a trusted server on a trusted network: the refs used to pin actions to commit hashes are fetched over this URL, and unencrypted traffic can be tampered with.
Before v11.16.0, update.ignoreDeps was named updateConfig.ignoreDependencies. The deprecated updateConfig setting keeps working until the next major version; when both are set, the update section takes precedence and a warning is printed.
supportedArchitectures
Ви можете вказати архітектури, для яких ви хочете встановити необовʼязкові залежності, навіть якщо вони не відповідають архітектурі системи, на якій виконується встановлення.
Наприклад, у наведеній нижче конфігурації вказано встановити необовʼязкові залежності для Windows x64:
supportedArchitectures:
os:
- win32
cpu:
- x64
Тоді як ця конфігурація встановить необовʼязкові залежності для Windows, macOS та архітектури системи, на якій наразі виконується встановлення. Вона включає артефакти як для x64, так і для arm64 процесорів:
supportedArchitectures:
os:
- win32
- darwin
- current
cpu:
- x64
- arm64
Крім того, supportedArchitectures також підтримує вказівку libc системи.
ignoredOptionalDependencies
Якщо необовʼязкова залежність має імʼя у цьому масиві, її буде пропущено. Наприклад:
ignoredOptionalDependencies:
- fsevents
- "@esbuild/*"
minimumReleaseAge
Додано у: v10.16.0
- Стандартно: 1440 (починаючи з v11), 0 (до v11)
- Тип: number (хвилини)
Щоб зменшити ризик встановлення скомпрометованих пакунків, ви можете відкласти встановлення щойно опублікованих версій. У більшості випадків шкідливі релізи виявляються та видаляються з реєстру протягом години.
minimumReleaseAge визначає мінімальну кількість хвилин, яка має пройти після публікації версії, перш ніж pnpm її встановить. Це стосується всіх залежностей, включаючи транзитивні.
Наприклад, наступне налаштування гарантує, що можна встановлювати лише пакунки, випущені щонайменше один день тому:
minimumReleaseAge: 1440
minimumReleaseAgeExclude
Додано у: v10.16.0
- Стандартно: undefined
- Тип: string[]
Якщо ви встановили minimumReleaseAge, але вам потрібні певні залежності, щоб завжди негайно встановлювати найновішу версію, ви можете перерахувати їх у розділі minimumReleaseAgeExclude. Виключення працює за назвою пакунка та застосовується до всіх версій цього пакунка.
Приклад:
minimumReleaseAge: 1440
minimumReleaseAgeExclude:
- webpack
- react
У цьому випадку всі залежності повинні бути віком щонайменше один день, окрім webpack та react, які встановлюються одразу після релізу.
Додано у: v10.17.0
Також ви можете використовувати шаблони. Наприклад, дозвольте всі пакунки з вашої організації:
minimumReleaseAge: 1440
minimumReleaseAgeExclude:
- '@myorg/*'
Додано у: v10.19.0
Ви також можете виключити певні версії (або список певних версій, використовуючи дизʼюнкцію з ||). Це дозволяє привʼязувати винятки до правил зрілості:
minimumReleaseAge: 1440
minimumReleaseAgeExclude:
- nx@21.6.5
- webpack@4.47.0 || 5.102.1
minimumReleaseAgeExcludePrune
Added in: v11.22.0
- Стандартно: false
- Тип: Boolean
When set to true, pnpm add, pnpm update, and pnpm remove prune the entries of minimumReleaseAgeExclude in pnpm-workspace.yaml that the freshly written lockfile no longer resolves: a version that is gone is dropped (an entry is removed once none of its versions remain), and an entry for a package that is no longer in the lockfile is removed too. Name patterns (@myorg/*) are always kept.
The cleanup is skipped when the install's lockfile does not cover the whole workspace (sharedWorkspaceLockfile: false), since entries another project still needs would look stale.
minimumReleaseAgeIgnoreMissingTime
Додано у: v11.0.0
- Стандартно: true
- Тип: Boolean
When true, pnpm skips the minimumReleaseAge check for a package whose registry metadata does not include the time field (some private registries and mirrors omit it). Set to false to fail resolution in that case instead of installing the package.
minimumReleaseAgeIgnoreMissingTime: false
minimumReleaseAgeStrict
Додано у: v11.0.0
- Стандартно: true якщо
minimumReleaseAgeналаштовано явним чином, false — в іншому випадку - Тип: Boolean
Controls how pnpm behaves when no version of a dependency satisfies the minimumReleaseAge constraint within the requested range. When false, pnpm falls back to a version that doesn't meet the minimumReleaseAge constraint so installation can still succeed. When true, pnpm fails resolution instead.
The default depends on whether you configured minimumReleaseAge yourself: if you set it explicitly (via pnpm-workspace.yaml, the CLI, or environment variables), strict mode is on by default so the setting is enforced. The built-in default of minimumReleaseAge (1440 minutes) is non-strict for backward compatibility.
minimumReleaseAgeStrict: true
trustPolicy
Додано у: v10.21.0
- Стандартно: off
- Тип: no-downgrade | off
При встановленні значення no-downgrade pnpm видасть помилку, якщо рівень довіри до пакунка знизився порівняно з попередніми версіями. Наприклад, якщо пакунок раніше був опублікований надійним видавцем, але зараз має лише походження або не має доказів надійності, встановлення не відбудеться. Це допомагає запобігти встановленню потенційно небезпечних версій. Перевірки довіри базуються виключно на даті публікації, а не на semver. Пакунок не можна встановити, якщо будь-яка раніше опублікована версія мала більш надійні докази достовірності. Починаючи з версії 10.24.0, попередні версії ігноруються під час оцінки доказів надійності для не попередньої інсталяції, тому надійна попередня версія не може блокувати стабільну версію, яка не має доказів надійності.
trustPolicyExclude
Додано у: v10.22.0
- Стандартно: []
- Тип: string[]
Список селекторів пакунків, які слід виключити з перевірки політики довіри. Це дозволяє встановлювати певні пакунки або версії, навіть якщо вони не відповідають вимогам trustPolicy.
Наприклад:
trustPolicy: no-downgrade
trustPolicyExclude:
- 'chokidar@4.0.3'
- 'webpack@4.47.0 || 5.102.1'
- '@babel/core@7.28.5'
trustPolicyIgnoreAfter
Додано у: v10.27.0
- Стандартно: undefined
- Тип: number (хвилини)
Дозволяє ігнорувати перевірку політики довіри для пакунків, опублікованих більше зазначеної кількості хвилин тому. Це корисно під час увімкнення суворих політик довіри, оскільки дозволяє встановлювати старіші версії пакунків (які можуть не мати процесу публікації з підписами або походженням) без ручного виключення, за умови, що вони безпечні через свій вік.
trustLockfile
Додано у: v11.3.0
- Стандартно: false
- Тип: Boolean
When true, pnpm install skips the supply-chain verification pass that re-applies minimumReleaseAge and trustPolicy to every entry in the loaded lockfile. The install treats the lockfile as already trusted.
Useful in environments where the lockfile is effectively part of the trusted base — closed-source projects where every commit comes from a trusted author. A poisoned lockfile (one a contributor authored under a weaker policy than CI enforces) can slip through, so leave this false whenever outside collaborators can edit the lockfile.
On large workspaces the verification pass holds per-package registry metadata in memory for the duration of the install; disabling it cuts memory usage at the cost of the supply-chain check. Most projects with the default frozenLockfile CI workflow do not need to set this.
blockExoticSubdeps
Додано у: v10.26.0
- Стандартно: true
- Тип: Boolean
Якщо встановлено значення true, лише прямі залежності (ті, що перелічені у вашому кореневому файлі package.json) можуть використовувати екзотичні джерела (такі як репозиторії git або прямі URL-адреси tar-архівів). Усі перехідні залежності повинні бути встановлені з надійного джерела, такого як налаштований реєстр, локальні шляхи до файлів, посилання на робочі простори або надійні репозиторії GitHub (node, bun, deno).
Цей параметр допомагає захистити ланцюжок постачання залежностей, запобігаючи завантаженню коду з ненадійних місць перехідними залежностями.
Екзотичні джерела включають:
- Git-репозиторії (
git+ssh://...) - Прямі URL-посилання на tar-архіви (
https://.../package.tgz)
registries
Додано у: v11.0.0
- Стандартно: undefined
- Type: Record<string, RegistryDeclaration> or Record<string, string>
Declares the registries the project installs from. Since v11.23.0, each registry is declared once, keyed by its URL, with everything pnpm knows about it in the entry: the scopes routed to it, the bare-specifier prefix it answers to, and how the server lays out tarball URLs (serverType, supportsTimeField). The full description of each field is on the dedicated Registries page.
registries:
https://npm.corp.example.com/:
serverType: artifactory
scopes: ["@my-org", "@internal"]
prefix: work
The older shape, mapping scopes to URLs, is still accepted. The default key sets the main registry (equivalent to the registry .npmrc setting), and scoped keys configure registries for specific package scopes:
registries:
default: https://registry.npmjs.org/
"@my-org": https://private.example.com/
"@internal": https://nexus.corp.com/
The two shapes cannot be mixed in one map.
Since v11.11.0, this setting may also be defined in the global configuration file (config.yaml), which is useful for registries that should apply to every project on the machine rather than to a single repository. Only the routes (scopes and prefix) are read from there; serverType and supportsTimeField shape the lockfile, so they are read only from pnpm-workspace.yaml — see where the setting may live.
namedRegistries
Додано у: v11.1.0
- Стандартно: undefined
- Тип: Record<string, string>
Deprecated since v11.23.0: declare a prefix in registries instead — see the Registries page. namedRegistries is still read, but only for prefixes that registries does not declare; when both settings declare prefixes, pnpm warns. Everything below about aliases — the built-in ones, reserved names, and the lockfile keys — applies to prefix-declared aliases the same way.
Defines named registry aliases that can be used as a prefix when installing packages, in the style of vlt's named-registry aliases. For example, with the following configuration:
namedRegistries:
gh: https://npm.pkg.github.example.com/
work: https://npm.work.example.com/
pnpm add work:@corp/lib@^2.0.0 resolves @corp/lib@^2.0.0 against https://npm.work.example.com/.
Authentication is picked up from the existing per-URL .npmrc entries (e.g. //npm.pkg.github.com/:_authToken=...), so no separate auth mechanism is required.
Since v11.11.0, this setting may also be defined in the global configuration file (config.yaml), so an alias like work: can be shared across every project on the machine.
Built-in aliases
Two aliases work without any configuration:
| Alias | Реєстр | Примітки |
|---|---|---|
gh: | https://npm.pkg.github.com/ | The GitHub Packages npm registry. |
npmjs: | https://registry.npmjs.org/ | The public npm registry. Added in v11.20.0. |
Entries you define under namedRegistries are merged on top of these, so either one can be overridden — GitHub Enterprise Server users point gh at their own host, and an organization that mirrors or proxies npmjs should point npmjs at the mirror:
namedRegistries:
gh: https://npm.pkg.github.example.com/
npmjs: https://npm.internal.example.com/
npmjs: pins a dependency to the public registry even when the default registry points somewhere else, such as an internal proxy:
{
"dependencies": {
"left-pad": "npmjs:^1.3.0"
}
}
The npm: prefix cannot do this — it is the alias protocol (npm:<name>@<range>) and resolves through whatever registry points at.
The built-in URLs are also the prefixes that a tarball URL recorded in the lockfile is matched against when pnpm verifies a package. If you proxy npmjs and do not override the alias, an entry whose tarball URL is on registry.npmjs.org is verified against the public registry rather than against your mirror. This only affects lockfiles that record such a URL — a canonical URL for your configured registry is omitted from the lockfile — and only when a tarball-URL, minimumReleaseAge, or trustPolicy check runs.
Reserved alias names
Since v11.20.0, an alias that shadows a reserved dependency specifier prefix (file, link, workspace, runtime, npm, jsr, git, github, gitlab, bitbucket, catalog, custom, http, https, ssh) is rejected with ERR_PNPM_RESERVED_NAMED_REGISTRY_NAME. Previously such an alias was silently shadowed by the corresponding resolver. An alias must also start with a letter and contain only letters, digits, ., _, and -.
Named registries in the lockfile
Since v11.20.0, a package resolved from a named registry is recorded in pnpm-lock.yaml under a registry-qualified key, <name>@<registryName>:<version>:
packages:
foo@work:1.0.0:
resolution: {integrity: sha512-...}
Before v11.20.0, packages were keyed by name@version alone, so the same name and version served by two registries collapsed onto a single entry and whichever resolved first decided the tarball that every consumer got. That is a package-substitution risk: a package you expect from your private registry could be installed from another registry that publishes the same name and version, with nothing in the lockfile to reveal it. Registry-qualified keys give each registry its own entry and pin which one a dependency came from.
The lockfile format version is unchanged, and qualified keys appear only for packages resolved from a named registry — including the built-in gh: and npmjs: aliases, which need no namedRegistries entry. A project that installs nothing through an alias sees no difference, and older pnpm versions keep reading the file.
If any dependency is installed through an alias, your first non-frozen install on v11.20.0 or newer re-keys those entries, which shows up as a lockfile diff. Commit it — that diff is the fix being applied. Review it too: an entry that moves to a registry you did not expect is worth investigating.
Have everyone working on the project move to v11.20.0 or newer first. An older pnpm reads the re-keyed lockfile fine, and frozen installs are unaffected, but it does not produce registry-qualified keys itself: any install that updates the lockfile writes those entries back to the old shape, and the next install on a current pnpm re-qualifies them. The lockfile then flips back and forth, and while it is in the old shape the project is exposed again. Because the lockfile format version is deliberately unchanged, pnpm cannot detect this and warn you.
There is no setting to keep the old behavior — the old shape is the vulnerability.
Every non-built-in alias that the lockfile references must stay declared — through prefix in registries or through namedRegistries. Reading an entry whose alias is gone fails with ERR_PNPM_MISSING_NAMED_REGISTRY rather than falling back to the default registry, since that would fetch a different package. Renaming an alias re-resolves the packages that used it.
Tarball URLs that follow the standard registry layout are no longer written to the lockfile for named-registry packages; they are recomputed from the alias's declared URL on demand.