Перейти до основного змісту
Версія: 11.x

Налаштування (pnpm-workspace.yaml)

pnpm отримує свою конфігурацію з командного рядка, змінних оточення, файлівpnpm-workspace.yaml та .npmrc.

Команду pnpm config можна використовувати для читання та редагування вмісту файлів проєкту та файлів глобальної конфігурації.

Відповідні конфігураційні файли:

нотатка

Налаштування, пов'язані з авторизацією, обробляються через .npmrc.

Значення у файлах конфігурації можуть містити змінні env із використанням синтаксису ${NAME}. Змінні env також можуть бути вказані зі стандартними значеннями. Using ${NAME-fallback} will return fallback if NAME isn't set. ${NAME:-fallback} will return fallback if NAME isn't set, or is an empty string.

Розвʼязання залежностей

overrides

This field allows you to instruct pnpm to override any dependency in the dependency graph, including peer dependencies. Це корисно для того, щоб змусити всі ваші пакунки використовувати одну версію залежності, перенести виправлення, замінити залежність форком або видалити невикористовувану залежність.

Note that the overrides field can only be set at the root of the project.

Приклад поля overrides:

overrides:
"foo": "^1.0.0"
"quux": "npm:@myorg/quux@^1.0.0"
"bar@^2.1.0": "3.0.0"
"qar@1>zoo": "2"

You may specify the package the overridden dependency belongs to by separating the package selector from the dependency selector with a ">", for example qar@1>zoo will only override the zoo dependency of qar@1, not for any other dependencies.

Перевизначення можна визначити як посилання на специфікацію прямої залежності. This is achieved by prefixing the name of the dependency with a $:

package.json
{
"dependencies": {
"foo": "^1.0.0"
}
}
pnpm-workspace.yaml
overrides:
foo: "$foo"

Пакунок, на який посилаються, не обовʼязково повинен збігатися з пакунком, на який посилається перевизначений:

pnpm-workspace.yaml
overrides:
bar: "$foo"

Якщо ви вважаєте, що використання певного пакунка не потребує однієї з його залежностей, ви можете використовувати -, щоб вилучити її. Наприклад, якщо пакунок foo@1.0.0 потребує великого пакунка з назвою bar для функції, яку ви не використовуєте, вилучення цього пакунка може скоротити час встановлення:

overrides:
"foo@1.0.0>bar": "-"

This feature is especially useful with optionalDependencies, where most optional packages can be safely skipped.

Overriding peer dependencies

Overrides also apply to peerDependencies. The behavior depends on the type of version specifier used in the override:

  • Semver ranges (e.g., ^1.0.0), workspace, and catalog protocols: the peer dependency is overridden and remains a peer dependency.
  • Non-range specifiers such as link: or file: protocols: the peer dependency is overridden and moved to dependencies, since these are not valid peer dependency ranges.
  • Removal (-): the peer dependency is removed entirely.

For example, to override the react peer dependency of react-dom:

pnpm-workspace.yaml
overrides:
"react-dom>react": "18.1.0"

packageExtensions

The packageExtensions fields offer a way to extend the existing package definitions with additional information. For example, if react-redux should have react-dom in its peerDependencies but it has not, it is possible to patch react-redux using packageExtensions:

packageExtensions:
react-redux:
peerDependencies:
react-dom: "*"

The keys in packageExtensions are package names or package names and semver ranges, so it is possible to patch only some versions of a package:

packageExtensions:
react-redux@1:
peerDependencies:
react-dom: "*"

The following fields may be extended using packageExtensions: dependencies, optionalDependencies, peerDependencies, and peerDependenciesMeta.

A bigger example:

packageExtensions:
express@1:
optionalDependencies:
typescript: "2"
fork-ts-checker-webpack-plugin:
dependencies:
"@babel/core": "1"
peerDependencies:
eslint: ">= 6"
peerDependenciesMeta:
eslint:
optional: true
підказка

Together with Yarn, we maintain a database of packageExtensions to patch broken packages in the ecosystem. If you use packageExtensions, consider sending a PR upstream and contributing your extension to the @yarnpkg/extensions database.

allowedDeprecatedVersions

Цей параметр дозволяє вимкнути попередження про застарілість певних пакунків.

Приклад:

allowedDeprecatedVersions:
express: "1"
request: "*"

With the above configuration pnpm will not print deprecation warnings about any version of request and about v1 of express.

updateConfig

updateConfig.ignoreDependencies

Іноді ви не можете оновити залежність. Наприклад, остання версія залежності почала використовувати ESM, але ваш проєкт ще не в ESM. Annoyingly, such a package will be always printed out by the pnpm outdated command and updated, when running pnpm update --latest. However, you may list packages that you don't want to upgrade in the ignoreDependencies field:

updateConfig:
ignoreDependencies:
- load-json-file

Patterns are also supported, so you may ignore any packages from a scope: @babel/*.

supportedArchitectures

Ви можете вказати архітектури, для яких ви хочете встановити необовʼязкові залежності, навіть якщо вони не відповідають архітектурі системи, на якій виконується встановлення.

Наприклад, у наведеній нижче конфігурації вказано встановити необовʼязкові залежності для Windows x64:

supportedArchitectures:
os:
- win32
cpu:
- x64

Тоді як ця конфігурація встановить необовʼязкові залежності для Windows, macOS та архітектури системи, на якій наразі виконується встановлення. Вона включає артефакти як для x64, так і для arm64 процесорів:

supportedArchitectures:
os:
- win32
- darwin
- current
cpu:
- x64
- arm64

Additionally, supportedArchitectures also supports specifying the libc of the system.

ignoredOptionalDependencies

If an optional dependency has its name included in this array, it will be skipped. Наприклад:

ignoredOptionalDependencies:
- fsevents
- "@esbuild/*"

minimumReleaseAge

Додано у: v10.16.0

  • Стандартно: 0
  • Тип: number (хвилини)

Щоб зменшити ризик встановлення скомпрометованих пакунків, ви можете відкласти встановлення щойно опублікованих версій. У більшості випадків шкідливі релізи виявляються та видаляються з реєстру протягом години.

minimumReleaseAge визначає мінімальну кількість хвилин, яка має пройти після публікації версії, перш ніж pnpm її встановить. Це стосується всіх залежностей, включаючи транзитивні.

Наприклад, наступне налаштування гарантує, що можна встановлювати лише пакунки, випущені щонайменше один день тому:

minimumReleaseAge: 1440

minimumReleaseAgeExclude

Додано у: v10.16.0

  • Default: undefined
  • Type: 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

trustPolicy

Додано у: v10.21.0

  • Стандартно: off
  • Тип: no-downgrade | off

При встановленні значення no-downgrade pnpm видасть помилку, якщо рівень довіри до пакунка знизився порівняно з попередніми версіями. Наприклад, якщо пакунок раніше був опублікований надійним видавцем, але зараз має лише походження або не має доказів надійності, встановлення не відбудеться. Це допомагає запобігти встановленню потенційно небезпечних версій. Перевірки довіри базуються виключно на даті публікації, а не на semver. Пакунок не можна встановити, якщо будь-яка раніше опублікована версія мала більш надійні докази достовірності. Починаючи з версії 10.24.0, попередні версії ігноруються під час оцінки доказів надійності для не попередньої інсталяції, тому надійна попередня версія не може блокувати стабільну версію, яка не має доказів надійності.

trustPolicyExclude

Додано у: v10.22.0

  • Стандартно: []
  • Type: 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

  • Default: undefined
  • Тип: number (хвилини)

Дозволяє ігнорувати перевірку політики довіри для пакунків, опублікованих більше зазначеної кількості хвилин тому. Це корисно під час увімкнення суворих політик довіри, оскільки дозволяє встановлювати старіші версії пакунків (які можуть не мати процесу публікації з підписами або походженням) без ручного виключення, за умови, що вони безпечні через свій вік.

blockExoticSubdeps

Додано у: v10.26.0

  • Default: true
  • Тип: Boolean

Якщо встановлено значення true, лише прямі залежності (ті, що перелічені у вашому кореневому файлі package.json) можуть використовувати екзотичні джерела (такі як репозиторії git або прямі URL-адреси tar-архівів). Усі перехідні залежності повинні бути встановлені з надійного джерела, такого як налаштований реєстр, локальні шляхи до файлів, посилання на робочі простори або надійні репозиторії GitHub (node, bun, deno).

Цей параметр допомагає захистити ланцюжок постачання залежностей, запобігаючи завантаженню коду з ненадійних місць перехідними залежностями.

Екзотичні джерела включають:

  • Git-репозиторії (git+ssh://...)
  • Прямі URL-посилання на tar-архіви (https://.../package.tgz)

Налаштування підйому залежностей

hoist

  • Default: true
  • Type: boolean

When true, all dependencies are hoisted to node_modules/.pnpm/node_modules. This makes unlisted dependencies accessible to all packages inside node_modules.

hoistWorkspacePackages

  • Default: true
  • Type: boolean

Коли true, пакунки з робочих просторів буде звʼязано або з <workspace_root>/node_modules/.pnpm/node_modules, або з <workspace_root>/node_modules, залежно від інших параметрів підйому (hoistPattern та publicHoistPattern).

hoistPattern

  • Default: ['*']
  • Type: string[]

Tells pnpm which packages should be hoisted to node_modules/.pnpm/node_modules. Стандартно, всі пакунки буде піднято — однак, якщо ви знаєте, що лише деякі пакунки мають фантомні залежності, ви можете скористатися цим параметром, щоб підняти лише фантомні залежності (рекомендується).

Наприклад:

hoistPattern:
- "*eslint*"
- "*babel*"

You may also exclude patterns from hoisting using !.

Наприклад:

hoistPattern:
- "*types*"
- "!@types/react"

publicHoistPattern

  • Стандартно: []
  • Type: string[]

На відміну від hoistPattern , який підіймає залежності до прихованої теки модулів у віртуальному сховищі, publicHoistPattern підіймає залежності, що відповідають шаблону, до кореневої теки модулів. Підняття до кореневої теки модулів означає, що код застосунку матиме доступ до фантомних залежностей, навіть якщо вони неправильно змінять стратегію розвʼязання.

Цей параметр корисний при роботі з деякими недосконалими інструментами, що підключаються, які не обробляють залежності належним чином.

Наприклад:

publicHoistPattern:
- "*plugin*"

Зауваження: Встановлення shamefullyHoist у true аналогічно встановленню publicHoistPattern у *.

You may also exclude patterns from hoisting using !.

Наприклад:

publicHoistPattern:
- "*types*"
- "!@types/react"

shamefullyHoist

  • Стандартно: false
  • Тип: Boolean

Стандартно pnpm створює напівсувору теку node_modules, тобто залежності мають доступ до неоголошених залежностей, а модулі поза межами node_modules — ні. За такої схеми більшість пакунків в екосистемі працюють без проблем. However, if some tooling only works when the hoisted dependencies are in the root of node_modules, you can set this to true to hoist them for you.

Параметри модулів

modulesDir

  • Default: node_modules
  • Type: path

The directory in which dependencies will be installed (instead of node_modules).

nodeLinker

  • Default: isolated
  • Type: isolated, hoisted, pnp

Визначає, який компонувальник слід використовувати для встановлення пакунків Node.

  • isolated - dependencies are symlinked from a virtual store at node_modules/.pnpm.
  • hoisted - a flat node_modules without symlinks is created. Same as the node_modules created by npm or Yarn Classic. При використанні цього параметра для підйому використовується одна з бібліотек Yarn. Законні причини для використання цього налаштування:
    1. Ваші інструменти погано працюють із символічними посиланнями. A React Native project will most probably only work if you use a hoisted node_modules.
    2. Ваш проєкт буде розгорнуто на безсерверний хостинг. Деякі безсерверні провайдери (наприклад, AWS Lambda) не підтримують symlinks. Альтернативним розвʼязання цієї проблеми є пакування програми перед розгортанням.
    3. If you want to publish your package with "bundledDependencies".
    4. If you are running Node.js with the --preserve-symlinks flag.
  • pnp - no node_modules. Plug'n'Play is an innovative strategy for Node that is used by Yarn Berry. It is recommended to also set symlink setting to false when using pnp as your linker.
  • Default: true
  • Тип: Boolean

When symlink is set to false, pnpm creates a virtual store directory without any symlinks. Це корисний параметр разом з nodeLinker=pnp.

enableModulesDir

  • Default: true
  • Тип: Boolean

When false, pnpm will not write any files to the modules directory (node_modules). Це корисно, коли теку модулів змонтовано з файловою системою у просторі користувача (FUSE). There is an experimental CLI that allows you to mount a modules directory with FUSE: @pnpm/mount-modules.

virtualStoreDir

  • Default: node_modules/.pnpm
  • Types: path

Тека з посиланнями на сховище. Всі прямі та непрямі залежності проєкту повʼязані з цією текою.

Це корисний параметр, який може усунути проблеми з довгими шляхами у Windows. If you have some dependencies with very long paths, you can select a virtual store in the root of your drive (for instance C:\my-project-store).

Or you can set the virtual store to .pnpm and add it to .gitignore. Це зробить трасування стеку чистішим, оскільки шляхи до залежностей будуть на одну теку вище.

NOTE: the virtual store cannot be shared between several projects. Кожен проєкт повинен мати власне віртуальне сховище (за винятком робочих просторів, де корінь є спільним).

virtualStoreDirMaxLength

  • Стандартно:
    • У Linux/macOS: 120
    • У Windows: 60
  • Types: number

Sets the maximum allowed length of directory names inside the virtual store directory (node_modules/.pnpm). Ви можете встановити менше значення, якщо у вас виникають проблеми з довгими шляхами у Windows.

packageImportMethod

  • Default: auto
  • Type: auto, hardlink, copy, clone, clone-or-copy

Керує способом імпорту пакунків зі сховища (якщо ви хочете вимкнути symlinks всередині node_modules, то вам потрібно змінити параметр nodeLinker, а не цей).

  • auto - try to clone packages from the store. Якщо клонування не підтримується, встановіть жорстке посилання на пакунки зі сховища. Якщо ані клонування, ані звʼязування неможливі, поверніться до копіювання
  • hardlink - hard link packages from the store
  • clone-or-copy - try to clone packages from the store. Якщо клонування не підтримується, поверніться до копіювання
  • copy - copy packages from the store
  • clone - clone (AKA copy-on-write or reference link) packages from the store

Клонування — найкращий спосіб запису пакунків у node_modules. Це найшвидший і найбезпечніший спосіб. Коли використовується клонування, ви можете редагувати файли у ваших node_modules, і вони не будуть змінені у центральному сховищі з адресованим вмістом.

На жаль, не всі файлові системи підтримують клонування. Ми рекомендуємо використовувати файлову систему з копіюванням при записі (CoW) (наприклад, Btrfs замість Ext4 в Linux) для найкращого досвіду роботи з pnpm.

modulesCacheMaxAge

  • Default: 10080 (7 days in minutes)
  • Type: number

Час у хвилинах, через який слід видалити порожні пакунки з теки модулів. pnpm зберігає кеш пакунків у теці модулів. Це підвищує швидкість встановлення при перемиканні гілок або пониженню версій залежностей.

dlxCacheMaxAge

  • Default: 1440 (1 day in minutes)
  • Type: number

Час у хвилинах, через який закінчується кеш dlx. Після виконання команди dlx pnpm зберігає кеш, який пропускає крок встановлення для наступних викликів тієї самої команди dlx.

enableGlobalVirtualStore

Додано у: v10.12.1

  • Стандартно: false (завжди false в CI)
  • Тип: Boolean
  • Статус: Experimental

Якщо увімкнено, node_modules містить лише символьні посилання на центральне віртуальне сховище, а не на node_modules/.pnpm. Стандартно, це центральне сховище розташовано за адресою <store-path>/links (використовуйте pnpm store path, щоб знайти <store-path>).

У центральному віртуальному сховищі кожен пакунок жорстко повʼязаний з текою, назва якої є хешем його графа залежностей. В результаті, всі проєкти в системі можуть звʼязати свої залежності з цим спільним місцем на диску. Цей підхід концептуально подібний до того, як NixOS керує пакунками, використовуючи хеші графів залежностей для створення ізольованих та спільних тек пакунків у сховищі Nix.

Це не слід плутати з глобальним сховищем адресованого вмісту. Фактичні файли пакунків, як і раніше, жорстко повʼязані зі сховищем, що адресується за вмістом, але замість того, щоб бути повʼязаними безпосередньо з node_modules/.pnpm, вони повʼязані з глобальним віртуальним сховищем.

Використання глобального віртуального сховища може значно прискорити встановлення, якщо доступний «теплий» кеш. Однак у середовищі CI (де кеш зазвичай відсутній) це може сповільнити встановлення. Якщо pnpm виявляє, що він працює в CI, цей параметр автоматично вимикається.

important

Для підтримки піднятих залежностей при використанні глобального віртуального сховища pnpm покладається на змінну оточення NODE_PATH. Це дозволяє Node.js розпізнавати пакунки з піднятої теки node_modules. Однак цей обхідний шлях не працює з модулями ESM, оскільки Node.js більше не враховує NODE_PATH при використанні ESM.

Якщо ваші залежності є залежностями ESM і вони імпортують пакунки не оголошені у власному package.json (що вважається поганою практикою), ви, ймовірно, зіткнетеся з помилками при обробці. Виправити це можна двома способами:

  • Використовуйте packageExtensions для явного додавання відсутніх залежностей.
  • Додайте конфігураційну залежність @pnpm/plugin-esm-node-path до вашого проєкту. Цей втулок реєструє власний завантажувач ESM, який відновлює підтримку NODE_PATH для ESM, дозволяючи коректно вирішувати підняті залежності.

Налаштування сховища

storeDir

  • Стандартно:
    • If the $PNPM_HOME env variable is set, then $PNPM_HOME/store
    • If the $XDG_DATA_HOME env variable is set, then $XDG_DATA_HOME/pnpm/store
    • On Windows: ~/AppData/Local/pnpm/store
    • On macOS: ~/Library/pnpm/store
    • On Linux: ~/.local/share/pnpm/store
  • Type: path

Місце, де зберігаються всі пакунки на диску.

Сховище завжди має бути на тому самому диску, на якому відбувається встановлення, тому на кожному диску буде одне сховище. Якщо на поточному диску є домашня тека, то сховище створюється всередині неї. Якщо на диску немає домашньої теки, то сховище створюється у корені файлової системи. For example, if installation is happening on a filesystem mounted at /mnt, then the store will be created at /mnt/.pnpm-store. Те ж саме стосується і систем Windows.

Можна встановити сховище з іншого диска, але у цьому випадку pnpm копіюватиме пакунки зі сховища, а не звʼязуватиме їх жорсткими посиланнями, оскільки жорсткі посилання можливі лише у тій самій файловій системі.

verifyStoreIntegrity

  • Default: true
  • Тип: Boolean

By default, if a file in the store has been modified, the content of this file is checked before linking it to a project's node_modules. Якщо verifyStoreIntegrity встановлено у false, файли у сховищі з адресованим вмістом не буде перевірено під час встановлення.

useRunningStoreServer

небезпека

Застаріла функція

  • Стандартно: false
  • Тип: Boolean

Дозволяє встановлення лише з сервером сховища. Якщо жоден сервер сховища не запущено, інсталяція завершиться невдало.

strictStorePkgContentCheck

  • Default: true
  • Тип: Boolean

Деякі реєстри дозволяють публікувати один і той самий контент з різними назвами пакунків та/або версіями. Це порушує перевірку дійсності пакунків у сховищі. Щоб уникнути помилок при перевірці назв і версій таких пакунків у сховищі, ви можете встановити параметр strictStorePkgContentCheck у значення false.

Параметри Lockfile

lockfile

  • Default: true
  • Тип: Boolean

When set to false, pnpm won't read or generate a pnpm-lock.yaml file.

preferFrozenLockfile

  • Default: true
  • Тип: Boolean

When set to true and the available pnpm-lock.yaml satisfies the package.json dependencies directive, a headless installation is performed. Встановлення headless пропускає визначення всіх залежностей, оскільки йому не потрібно змінювати файл блокування.

lockfileIncludeTarballUrl

  • Стандартно: false
  • Тип: Boolean

Add the full URL to the package's tarball to every entry in pnpm-lock.yaml.

gitBranchLockfile

  • Стандартно: false
  • Тип: Boolean

When set to true, the generated lockfile name after installation will be named based on the current branch name to completely avoid merge conflicts. For example, if the current branch name is feature-foo, the corresponding lockfile name will be pnpm-lock.feature-foo.yaml instead of pnpm-lock.yaml. Зазвичай використовується разом з аргументом командного рядка --merge-git-branch-lockfiles або за допомогою параметра mergeGitBranchLockfilesBranchPattern у файлі pnpm-workspace.yaml.

mergeGitBranchLockfilesBranchPattern

  • Default: null
  • Type: Array or null

This configuration matches the current branch name to determine whether to merge all git branch lockfile files. By default, you need to manually pass the --merge-git-branch-lockfiles command line parameter. This configuration allows this process to be automatically completed.

Наприклад:

mergeGitBranchLockfilesBranchPattern:
- main
- release*

You may also exclude patterns using !.

peersSuffixMaxLength

  • Default: 1000
  • Type: number

Максимальна довжина суфікса ідентифікаторів прямих залежностей, що додається до ключів залежностей у файлі блокування. Якщо суфікс довший, він замінюється хешем.

Налаштування запиту

gitShallowHosts

  • Default: ['github.com', 'gist.github.com', 'gitlab.com', 'bitbucket.com', 'bitbucket.org']
  • Type: string[]

Під час отримання залежностей, які є Git-репозиторіями, якщо хост вказано у цьому параметрі, pnpm використовуватиме неглибоке клонування, щоб отримати лише потрібний комміт, а не всю історію.

networkConcurrency

  • Стандартно: auto (workers × 3, обмежено діапазоном 16-64)
  • Type: Number

Контролює максимальну кількість запитів HTTP(S) для одночасної обробки.

Починаючи з версії 10.24.0, pnpm автоматично вибирає значення від 16 до 64 залежно від кількості робітників (networkConcurrency = clamp(workers × 3, 16, 64)). Встановіть це значення явно, щоб перезаписати автоматичне масштабування.

fetchRetries

  • Default: 2
  • Type: Number

Скільки разів повторити спробу, якщо pnpm не вдається отримати дані з реєстру.

fetchRetryFactor

  • Default: 10
  • Type: Number

Експоненціальний коефіцієнт для повторної спроби.

fetchRetryMintimeout

  • Default: 10000 (10 seconds)
  • Type: Number

Мінімальний (базовий) тайм-аут для повторних запитів.

fetchRetryMaxtimeout

  • Default: 60000 (1 minute)
  • Type: Number

Максимальний таймаут очікування, щоб гарантувати, що фактор повторних спроб не робить запити занадто довгими.

fetchTimeout

  • Default: 60000 (1 minute)
  • Type: Number

Максимальний час очікування виконання HTTP-запитів.

fetchWarnTimeoutMs

Додано у: v10.18.0

  • Стандартно: 10000 ms (10 секунд)
  • Type: Number

Якщо запит метаданих до реєстру триває довше, ніж зазначений поріг (у мілісекундах), виводиться попередження.

fetchMinSpeedKiBps

Додано у: v10.18.0

  • Стандартно: 50 KiB/s
  • Type: Number

Попередження виводиться, якщо швидкість завантаження архіву з реєстру падає нижче заданого порогу (в КіБ/с).

Параметри прямих залежностей

autoInstallPeers

  • Default: true
  • Тип: Boolean

When true, any missing non-optional peer dependencies are automatically installed.

Конфлікт версій

Якщо існують суперечливі вимоги до версій для прямої залежності з різних пакунків, pnpm не встановлюватиме автоматично жодну з версій суперечливої прямої залежності. Натомість виводиться попередження. For example, if one dependency requires react@^16.0.0 and another requires react@^17.0.0, these requirements conflict, and no automatic installation will occur.

Розвʼязання конфліктів

У випадку конфлікту версій вам потрібно буде визначити, яку версію прямої залежності встановити самостійно, або оновити залежності, щоб узгодити їхні вимоги до прямих залежностей.

dedupePeerDependents

  • Default: true
  • Тип: Boolean

When this setting is set to true, packages with peer dependencies will be deduplicated after peers resolution.

For instance, let's say we have a workspace with two projects and both of them have webpack in their dependencies. webpack has esbuild in its optional peer dependencies, and one of the projects has esbuild in its dependencies. In this case, pnpm will link two instances of webpack to the node_modules/.pnpm directory: one with esbuild and another one without it:

node_modules
.pnpm
webpack@1.0.0_esbuild@1.0.0
webpack@1.0.0
project1
node_modules
webpack -> ../../node_modules/.pnpm/webpack@1.0.0/node_modules/webpack
project2
node_modules
webpack -> ../../node_modules/.pnpm/webpack@1.0.0_esbuild@1.0.0/node_modules/webpack
esbuild

This makes sense because webpack is used in two projects, and one of the projects doesn't have esbuild, so the two projects cannot share the same instance of webpack. However, this is not what most developers expect, especially since in a hoisted node_modules, there would only be one instance of webpack. Отже, тепер ви можете використовувати параметр dedupePeerDependents для дедуплікації webpack, якщо він не має конфліктні прямі залежності (пояснення у кінці). У цьому випадку, якщо ми встановимо dedupePeerDependents у true, обидва проєкти використовуватимуть той самий екземпляр webpack, який має esbuild:

node_modules
.pnpm
webpack@1.0.0_esbuild@1.0.0
project1
node_modules
webpack -> ../../node_modules/.pnpm/webpack@1.0.0_esbuild@1.0.0/node_modules/webpack
project2
node_modules
webpack -> ../../node_modules/.pnpm/webpack@1.0.0_esbuild@1.0.0/node_modules/webpack
esbuild

What are conflicting peer dependencies? By conflicting peer dependencies we mean a scenario like the following one:

node_modules
.pnpm
webpack@1.0.0_react@16.0.0_esbuild@1.0.0
webpack@1.0.0_react@17.0.0
project1
node_modules
webpack -> ../../node_modules/.pnpm/webpack@1.0.0/node_modules/webpack
react (v17)
project2
node_modules
webpack -> ../../node_modules/.pnpm/webpack@1.0.0_esbuild@1.0.0/node_modules/webpack
esbuild
react (v16)

In this case, we cannot dedupe webpack as webpack has react in its peer dependencies and react is resolved from two different versions in the context of the two projects.

strictPeerDependencies

  • Стандартно: false
  • Тип: Boolean

Якщо цей параметр увімкнено, команди не будуть виконуватися, якщо у дереві відсутня або невірна залежність від прямої залежності.

resolvePeersFromWorkspaceRoot

  • Default: true
  • Тип: Boolean

Якщо увімкнено, залежності кореневого проєкту робочої області використовуються для розвʼязання прямих залежностей будь-яких проєктів у робочій області. Це корисна функція, оскільки ви можете встановлювати прямі залежності лише у корені робочого простору, і ви можете бути впевнені, що всі проєкти у робочому просторі використовують однакові версії прямих залежностей.

peerDependencyRules

peerDependencyRules.ignoreMissing

pnpm will not print warnings about missing peer dependencies from this list.

For instance, with the following configuration, pnpm will not print warnings if a dependency needs react but react is not installed:

peerDependencyRules:
ignoreMissing:
- react

Також можна використовувати шаблони назв пакунків:

peerDependencyRules:
ignoreMissing:
- "@babel/*"
- "@eslint/*"

peerDependencyRules.allowedVersions

Unmet peer dependency warnings will not be printed for peer dependencies of the specified range.

For instance, if you have some dependencies that need react@16 but you know that they work fine with react@17, then you may use the following configuration:

peerDependencyRules:
allowedVersions:
react: "17"

This will tell pnpm that any dependency that has react in its peer dependencies should allow react v17 to be installed.

It is also possible to suppress the warnings only for peer dependencies of specific packages. For instance, with the following configuration react v17 will be only allowed when it is in the peer dependencies of the button v2 package or in the dependencies of any card package:

peerDependencyRules:
allowedVersions:
"button@2>react": "17",
"card>react": "17"

peerDependencyRules.allowAny

allowAny is an array of package name patterns, any peer dependency matching the pattern will be resolved from any version, regardless of the range specified in peerDependencies. Наприклад:

peerDependencyRules:
allowAny:
- "@babel/*"
- "eslint"

The above setting will mute any warnings about peer dependency version mismatches related to @babel/ packages or eslint.

Параметри CLI

[no-]color

  • Default: auto
  • Type: auto, always, never

Керує кольорами у виводі.

  • auto - output uses colors when the standard output is a terminal or TTY.
  • always - ignore the difference between terminals and pipes. You’ll rarely want this; in most scenarios, if you want color codes in your redirected output, you can instead pass a --color flag to the pnpm command to force it to use color codes. Стандартні налаштування майже завжди відповідають вашим потребам.
  • never - turns off colors. This is the setting used by --no-color.

loglevel

  • Default: info
  • Type: debug, info, warn, error

Будуть показані всі журнали вказаного рівня або вище. You can instead pass --silent to turn off all output logs.

useBetaCli

  • Стандартно: false
  • Тип: Boolean

Експериментальна опція, яка дозволяє використовувати бета-функції CLI. Це означає, що ви можете отримати деякі зміни у функціоналі CLI, які є порушеннями або потенційними помилками.

recursiveInstall

  • Default: true
  • Тип: Boolean

If this is enabled, the primary behaviour of pnpm install becomes that of pnpm install -r, meaning the install is performed on all workspace or subdirectory packages.

Else, pnpm install will exclusively build the package in the current directory.

engineStrict

  • Стандартно: false
  • Тип: Boolean

Якщо цей параметр увімкнено, pnpm не встановлюватиме пакунки, які стверджують, що вони несумісні з поточною версією Node.

Regardless of this configuration, installation will always fail if a project (not a dependency) specifies an incompatible version in its engines field.

npmPath

  • Type: path

Розташування бінарного файлу npm, який pnpm використовує для деяких дій, таких як публікація.

packageManagerStrict

  • Default: true
  • Тип: Boolean

If this setting is disabled, pnpm will not fail if a different package manager is specified in the packageManager field of package.json. When enabled, only the package name is checked (since pnpm v9.2.0), so you can still run any version of pnpm regardless of the version specified in the packageManager field.

Alternatively, you can disable this setting by setting the COREPACK_ENABLE_STRICT environment variable to 0.

packageManagerStrictVersion

  • Стандартно: false
  • Тип: Boolean

When enabled, pnpm will fail if its version doesn't exactly match the version specified in the packageManager field of package.json.

managePackageManagerVersions

  • Default: true
  • Тип: Boolean

When enabled, pnpm will automatically download and run the version of pnpm specified in the packageManager field of package.json. Це те саме поле, що використовується Corepack. Приклад:

{
"packageManager": "pnpm@9.3.0"
}

Параметри збирання

ignoreScripts

  • Стандартно: false
  • Тип: Boolean

Do not execute any scripts defined in the project package.json and its dependencies.

нотатка

This flag does not prevent the execution of .pnpmfile.mjs

ignoreDepScripts

  • Стандартно: false
  • Тип: Boolean

Не виконувати жодних скриптів встановлених пакунків. Скрипти проєктів виконуються.

нотатка

Since v10, pnpm doesn't run the lifecycle scripts of dependencies unless they are listed in allowBuilds.

childConcurrency

  • Default: 5
  • Type: Number

Максимальна кількість дочірніх процесів, які можна одночасно виділити для збірки node_modules.

sideEffectsCache

  • Default: true
  • Тип: Boolean

Використовувати та кешувати результати хуків (пре/пост)встановлення.

Коли скрипти (пре/пост)встановлення змінюють вміст пакунка (наприклад, вивід даних збірки), pnpm зберігає змінений пакунок у глобальному сховищі. При наступних інсталяціях на тій самій машині pnpm повторно використовує цю кешовану, попередньо зібрану версію, завдяки чому інсталяції відбуваються значно швидше.

нотатка

Можливо, ви захочете вимкнути цей параметр, якщо:

  1. Скрипти встановлення змінюють файли поза текою пакунків (pnpm не може відстежувати або кешувати ці зміни).
  2. Скрипти виконують побічні ефекти, не повʼязані зі збіркою пакунка.

sideEffectsCacheReadonly

  • Стандартно: false
  • Тип: Boolean

Використовувати кеш побічних ефектів лише за наявності, не створювати його для нових пакунків.

unsafePerm

  • Default: false IF running as root, ELSE true
  • Тип: Boolean

Встановіть значення true, щоб увімкнути перемикання UID/GID під час запуску скриптів пакунків. Якщо явно вказати значення false, то встановлення від імені не root-користувача не вдасться.

nodeOptions

  • Default: NULL
  • Type: String

Options to pass through to Node.js via the NODE_OPTIONS environment variable. This does not impact how pnpm itself is executed but it does impact how lifecycle scripts are called.

Щоб зберегти наявні NODE_OPTIONS, ви можете звернутися до поточної змінної оточення за допомогою ${NODE_OPTIONS} у вашій конфігурації:

nodeOptions: "${NODE_OPTIONS:- } --experimental-vm-modules"

verifyDepsBeforeRun

  • Стандартно: false
  • Тип: install, warn, error, prompt, false

Цей параметр дозволяє перевіряти стан залежностей перед запуском сценаріїв. Перевірка виконується для команд pnpm run і pnpm exec. Підтримуються наступні значення:

  • install — Автоматично запускає встановлення, якщо node_modules не оновлено.
  • warn — Виводить попередження, якщо вміст node_modules не є актуальним.
  • prompt — Запитує у користувача дозвіл на запуск встановлення, якщо node_modules не оновлено.
  • error — Викликає помилку, якщо node_modules не є актуальним.
  • false — Вимикає перевірку залежностей.

strictDepBuilds

Додано у: v10.3.0

  • Default: true
  • Тип: Boolean

Якщо увімкнено strictDepBuilds , інсталяція завершуватиметься з ненульовим кодом завершення, якщо будь-які залежності мають нерецензовані скрипти збірки (так звані післяінсталяційні скрипти).

allowBuilds

Додано у: v10.26.0

A map of package matchers to explicitly allow (true) or disallow (false) script execution.

allowBuilds:
esbuild: true
core-js: false
nx@21.6.4 || 21.6.5: true

Default behavior: Packages not listed in allowBuilds are disallowed by default and an error is printed (since strictDepBuilds is true by default). If strictDepBuilds is set to false, a warning is printed instead.

dangerouslyAllowAllBuilds

Додано у: v10.9.0

  • Стандартно: false
  • Тип: Boolean

Якщо встановлено значення true, усі скрипти збірки (наприклад, preinstall, install, postinstall) з залежностей будуть виконуватися автоматично, без необхідності схвалення.

попередження

Цей параметр дозволяє всім залежностям, включно з перехідними, запускати сценарії встановлення, як зараз, так і в майбутньому. Навіть якщо ваш поточний граф залежності здається безпечним:

  • У майбутніх оновленнях можуть зʼявитися нові ненадійні залежності.
  • До наявних пакунків можуть бути додані скрипти у пізніших версіях.
  • Пакунки можуть бути перехоплені або скомпрометовані і почати виконувати шкідливий код.

Для максимальної безпеки вмикайте цю функцію, тільки якщо ви повністю усвідомлюєте ризики і довіряєте всій екосистемі, з якої ви отримуєте дані. Рекомендується переглядати і дозволяти збірки явним чином.

Параметри Node.js

nodeVersion

  • Default: the value returned by node -v, without the v prefix
  • Тип: точна версія semver (не діапазон)

The Node.js version to use when checking a package's engines setting.

Якщо ви хочете заборонити учасникам вашого проєкту додавати нові несумісні залежності, використовуйте nodeVersion та engineStrict у файлі pnpm-workspace.yaml у корені проєкту:

nodeVersion: 12.22.0
engineStrict: true

Таким чином, навіть якщо хтось використовує Node.js v16, він не зможе встановити нову залежність, яка не підтримує Node.js v12.22.0.

node-mirror

  • Default: https://nodejs.org/download/<releaseDir>/
  • Type: URL

Задає базову URL-адресу для завантаження Node.js. The <releaseDir> portion of this setting can be any directory from https://nodejs.org/download: release, rc, nightly, v8-canary, etc.

Ось як можна налаштувати pnpm для завантаження Node.js з дзеркала Node.js в Китаї:

node-mirror:release=https://npmmirror.com/mirrors/node/
node-mirror:rc=https://npmmirror.com/mirrors/node-rc/
node-mirror:nightly=https://npmmirror.com/mirrors/node-nightly/

Інші налаштування

savePrefix

  • Default: '^'
  • Type: '^', '~', ''

Configure how versions of packages installed to a package.json file get prefixed.

For example, if a package has version 1.2.3, by default its version is set to ^1.2.3 which allows minor upgrades for that package, but after pnpm config set save-prefix='~' it would be set to ~1.2.3 which only allows patch upgrades.

Цей параметр ігнорується, якщо доданий пакунок має вказаний діапазон. Наприклад, pnpm add foo@2 встановить версію foo у package.json на 2, незалежно від значення savePrefix .

tag

  • Default: latest
  • Type: String

If you pnpm add a package and you don't provide a specific version, then it will install the package at the version registered under the tag from this setting.

This also sets the tag that is added to the package@version specified by the pnpm tag command if no explicit tag is given.

globalDir

  • Стандартно:
    • If the $XDG_DATA_HOME env variable is set, then $XDG_DATA_HOME/pnpm/global
    • On Windows: ~/AppData/Local/pnpm/global
    • On macOS: ~/Library/pnpm/global
    • On Linux: ~/.local/share/pnpm/global
  • Type: path

Вкажіть власну теку для зберігання глобальних пакунків.

globalBinDir

  • Стандартно:
    • If the $XDG_DATA_HOME env variable is set, then $XDG_DATA_HOME/pnpm
    • On Windows: ~/AppData/Local/pnpm
    • On macOS: ~/Library/pnpm
    • On Linux: ~/.local/share/pnpm
  • Type: path

Дозволяє задати цільову теку для bin-файлів глобально встановлених пакунків.

stateDir

  • Стандартно:
    • If the $XDG_STATE_HOME env variable is set, then $XDG_STATE_HOME/pnpm
    • On Windows: ~/AppData/Local/pnpm-state
    • On macOS: ~/.pnpm-state
    • On Linux: ~/.local/state/pnpm
  • Type: path

The directory where pnpm creates the pnpm-state.json file that is currently used only by the update checker.

cacheDir

  • Стандартно:
    • If the $XDG_CACHE_HOME env variable is set, then $XDG_CACHE_HOME/pnpm
    • On Windows: ~/AppData/Local/pnpm-cache
    • On macOS: ~/Library/Caches/pnpm
    • On Linux: ~/.cache/pnpm
  • Type: path

Розташування кешу (метадані пакунків та dlx).

useStderr

  • Стандартно: false
  • Тип: Boolean

Якщо значення true, весь вивід записується у stderr.

updateNotifier

  • Default: true
  • Тип: Boolean

Set to false to suppress the update notification when using an older version of pnpm than the latest.

preferSymlinkedExecutables

  • Default: true, when node-linker is set to hoisted and the system is POSIX
  • Тип: Boolean

Create symlinks to executables in node_modules/.bin instead of command shims. Цей параметр ігнорується у Windows, де працюють лише командні shims.

ignoreCompatibilityDb

  • Стандартно: false
  • Тип: Boolean

Під час встановлення автоматично виправляються залежності деяких пакунків. Якщо ви хочете вимкнути цей параметр, встановіть для нього значення true.

The patches are applied from Yarn's @yarnpkg/extensions package.

resolutionMode

  • Default: highest (was lowest-direct from v8.0.0 to v8.6.12)
  • Type: highest, time-based, lowest-direct

Коли resolutionMode встановлено у time-based, залежності буде розвʼязано у такий спосіб:

  1. Прямі залежності будуть вирішені до найнижчих версій. So if there is foo@^1.1.0 in the dependencies, then 1.1.0 will be installed.
  2. Підзалежності будуть врегульовані, починаючи з версій, які були опубліковані до того, як була опублікована остання пряма залежність.

У цьому режимі встановлення з "теплим" кеш відбувається швидше. Це також зменшує ймовірність перехоплення підзалежностей, оскільки підзалежності будуть оновлюватися лише тоді, коли оновлюються прямі залежності.

This resolution mode works only with npm's full metadata. Тому в деяких сценаріях це відбувається повільніше. Однак, якщо ви використовуєте Verdaccio v5.15.1 або новішу версію, ви можете встановити параметр registrySupportsTimeField у значення true, і він працюватиме дуже швидко.

Коли resolutionMode встановлено у lowest-direct, прямі залежності буде розвʼязано до їх найнижчих версій.

registrySupportsTimeField

  • Стандартно: false
  • Тип: Boolean

Set this to true if the registry that you are using returns the "time" field in the abbreviated metadata. As of now, only Verdaccio from v5.15.1 supports this.

extendNodePath

  • Default: true
  • Тип: Boolean

When true, pnpm sets the NODE_PATH environment variable in command shims (the wrapper scripts created in node_modules/.bin). When false, NODE_PATH is not set.

Why this is needed

pnpm's isolated node_modules layout means that a package can only access its own declared dependencies. However, when a CLI tool runs via a command shim, some libraries (notably import-local, used by jest, eslint, and others) resolve modules from the current working directory rather than from the binary's own location. Since the working directory is the project root — not the package inside the virtual store — the standard node_modules resolution from the CWD won't find the binary's transitive dependencies.

To bridge this gap, pnpm includes two types of paths in NODE_PATH:

  1. The package's own dependencies directory (e.g., .pnpm/pkg@version/node_modules) — this allows CWD-based resolution to find the correct versions of the package's sibling dependencies.
  2. The hoisted node_modules directory (e.g., .pnpm/node_modules) — this is the directory where hoisted packages are placed when hoistPattern is set. Node.js cannot discover this directory through its standard resolution algorithm, so it must be provided via NODE_PATH.

NODE_PATH is also essential when enableGlobalVirtualStore is enabled. With a global virtual store, packages are symlinked from a central location outside the project, so Node.js's standard upward node_modules traversal from the binary's real path won't reach the project's own node_modules or its hoisted dependencies. In this case, NODE_PATH must include both the project's root node_modules and the hoisted directory at node_modules/.pnpm/node_modules to ensure correct resolution.

When to disable

You may set this to false if you are certain that none of the CLI tools in your project resolve modules from the working directory and you are not using a global virtual store. Disabling it produces slightly simpler command shims.

deployAllFiles

  • Стандартно: false
  • Тип: Boolean

When deploying a package or installing a local package, all files of the package are copied. By default, if the package has a "files" field in the package.json, then only the listed files and directories are copied.

dedupeDirectDeps

  • Стандартно: false
  • Тип: Boolean

When set to true, dependencies that are already symlinked to the root node_modules directory of the workspace will not be symlinked to subproject node_modules directories.

optimisticRepeatInstall

Додано у: v10.1.0

  • Стандартно: false
  • Тип: Boolean

Якщо увімкнено, буде виконано швидку перевірку перед початком інсталяції. Таким чином, повторне встановлення або встановлення в проєкті з усіма оновленнями стає набагато швидшим.

requiredScripts

Scripts listed in this array will be required in each project of the workspace. Otherwise, pnpm -r run <script name> will fail.

requiredScripts:
- build

enablePrePostScripts

  • Default: true
  • Тип: Boolean

When true, pnpm will run any pre/post scripts automatically. So running pnpm foo will be like running pnpm prefoo && pnpm foo && pnpm postfoo.

scriptShell

  • Default: null
  • Type: path

The shell to use for scripts run with the pnpm run command.

For instance, to force usage of Git Bash on Windows:

pnpm config set scriptShell "C:\Program Files\git\bin\bash.exe"

shellEmulator

  • Стандартно: false
  • Тип: Boolean

When true, pnpm will use a JavaScript implementation of a bash-like shell to execute scripts.

This option simplifies cross-platform scripting. For instance, by default, the next script will fail on non-POSIX-compliant systems:

"scripts": {
"test": "NODE_ENV=test node test.js"
}

Але якщо для параметра shellEmulator встановлено значення true, він працюватиме на всіх платформах.

нотатка

Node.js 22 або вище підтримує виконання скриптів без допомоги pnpm. Для наведеного вище прикладу ви можете запустити скрипт test за допомогою команди node --run test. Однак опція shellEmulator не впливає на це. Скрипти, що залежать від функцій POSIX, повинні виконуватися за допомогою команди pnpm run замість node --run, щоб працювати в середовищах, що не відповідають стандарту POSIX.

catalogMode

Додано у: v10.12.1

  • Стандартно: manual
  • Тип: manual, strict, prefer

Керує тим, чи додаються залежності до стандартного каталогу при виконанні pnpm add, і якщо так, то як саме. Є три режими:

  • strict — дозволяє лише версії залежностей з каталогу. Додавання залежності за межами діапазону версій каталогу призведе до помилки.
  • prefer — надає перевагу версіям з каталогу, але повертається до прямих залежностей, якщо сумісну версію не знайдено.
  • manual (стандартно) — не додає автоматично залежності до каталогу.

ci

Додано у: v10.12.1

  • Стандартно: true (коли середовище визначається як CI)
  • Тип: Boolean

Цей параметр явно вказує pnpm, чи є поточне середовище середовищем CI (безперервної інтеграції).

cleanupUnusedCatalogs

Додано у: v10.15.0

  • Стандартно: false
  • Тип: Boolean

Якщо встановлено значення 'true', pnpm видалить невикористані записи каталогів під час встановлення.