Інші налаштування
savePrefix#
- Стандартно: '^'
- Type: '^', '~', '', '='
Налаштуйте спосіб префіксації версій пакунків, встановлених до файлу package.json.
Наприклад, якщо пакунок має версію 1.2.3, стандартно його версію встановлено як ^1.2.3, що дозволяє незначні оновлення для цього пакунка, але після pnpm config set save-prefix='~' його буде встановлено як ~1.2.3, що дозволяє лише оновлення патчів.
With =, newly added dependencies are saved with an
explicit = operator (=1.2.3), which pins the exact version. pnpm update
keeps the = operator when it updates such a pin.
Цей параметр ігнорується, якщо доданий пакунок має вказаний діапазон. Наприклад, pnpm add foo@2 встановить версію foo у package.json на 2, незалежно від значення savePrefix .
saveExact#
- Стандартно: false
- Тип: Boolean
When set to true, pnpm add saves the resolved version without a range
operator, as the --save-exact CLI option does.
saveTypes#
Added in: v12.6.0
- Стандартно: false
- Тип: Boolean
When set to true, pnpm add saves available @types/* packages in
devDependencies alongside registry dependencies. Packages that declare bundled
TypeScript types are skipped.
saveTypes: true
You can also pass it as a CLI flag: pnpm add --save-types express.
tag#
- Стандартно: latest
- Типи: String
If you pnpm add a package and you don't provide a specific version, pnpm
saves the first of these that exists:
- A
catalog:reference, if the catalog pnpm saves to lists the package. - The range that every other workspace project declaring the package uses.
pnpm skips this step when the projects declare different ranges or one of
them uses a protocol, such as
workspace:. - The range a matching override sets.
- The version registered under the tag from this setting.
pnpm publish also publishes under this tag when --tag is not passed.
globalDir#
- Стандартно:
- If the $PNPM_HOME env variable is set, then $PNPM_HOME/global
- Якщо встановлено змінну середовища $XDG_DATA_HOME, тоді $XDG_DATA_HOME/pnpm/global
- У Windows: ~/AppData/Local/pnpm/global
- В macOS: ~/Library/pnpm/global
- У Linux: ~/.local/share/pnpm/global
- Тип: path
Вкажіть власну теку для зберігання глобальних пакунків. pnpm stores the packages
in a v11 subdirectory of this directory.
globalBinDir#
- Стандартно:
- If the $PNPM_HOME env variable is set, then $PNPM_HOME/bin
- Якщо встановлено змінну середовища $XDG_DATA_HOME, тоді $XDG_DATA_HOME/pnpm/bin
- У Windows: ~/AppData/Local/pnpm/bin
- В macOS: ~/Library/pnpm/bin
- У Linux: ~/.local/share/pnpm/bin
- Тип: path
Дозволяє задати цільову теку для bin-файлів глобально встановлених пакунків.
globalShims#
Added in: v12.0.0-rc.2
- Default: { node: auto, deno: auto, bun: auto }
- Type: Boolean, Object
Controls which globally installed packages get project-aware shims: global commands that run the version the current project asks for instead of the globally installed one.
The setting is a map from package name to policy. The key is the name of the package that provides the command, not the command itself, so an entry for typescript covers its tsc bin.
globalShims:
node: auto
deno: false
typescript: prompt
The supported policies are:
| Value | Поведінка |
|---|---|
auto (or true) |
Switch automatically when the candidate is authenticated by a publisher signature; otherwise ask for confirmation once. |
prompt |
Put every candidate through the confirmation gate, including signature-verified ones. Answers are still remembered, so this asks once per project and candidate, not on every run. |
always |
Always switch, never ask. Usable in CI, where a prompt would fall back to the global version. |
false |
Disable the project-aware shim for this package. |
Since v12.0.0-rc.6, two commands write entries here for you: pnpm shim add <pkg> records the package it links a shim for, and installing a package manager globally (pnpm add -g yarn) records that package manager so it follows a project's pin. Neither overwrites an entry you set yourself, including false, and including a globalShims: false that turns every shim off.
Layers merge key by key over the built-in defaults, so a single entry can change one package without restating the rest. globalShims: { bun: false } leaves node and deno at auto.
The scalar shorthands replace the whole map instead of merging: globalShims: false disables every project-aware shim, and globalShims: true resets to the defaults.
попередження
This setting is only read from locations a project cannot write to: the global configuration file, a pnpm-workspace.yaml in the pnpm home directory itself, and the PNPM_CONFIG_GLOBAL_SHIMS environment variable (a JSON value), applied in that order. A project's own pnpm-workspace.yaml is ignored. Otherwise a repository could grant itself the right to run its own binaries in place of your global ones.
Disabling a package, or changing its policy, takes effect on the very next command. The setting is re-read on each dispatch, so no reinstall is needed.
Newly enabling a package is the exception. pnpm decides at install time which bins to write dispatching shims for, so a package that was already installed globally while it was disabled needs to be reinstalled to pick up the change:
pnpm add -g typescript
To bypass dispatch for a single invocation, set PNPM_SHIM_BYPASS=1:
PNPM_SHIM_BYPASS=1 node --version
нотатка
Project-aware shims are a pnpm v12 feature and are not available in v11.
npmrcAuthFile#
- Стандартно: ~/.npmrc
- Тип: path
Шлях до файлу, що містить токени автентифікації реєстру. У стандартній конфігурації pnpm зчитує токени автентифікації з файлу ~/.npmrc як запасний варіант для автентифікації в реєстрі. Використовуйте цей параметр, щоб вказати на інший файл.
This setting cannot be set in pnpm-workspace.yaml at the project level; set it in the global configuration file, via the --npmrc-auth-file CLI option, or via the PNPM_CONFIG_NPMRC_AUTH_FILE environment variable (the npm-style NPM_CONFIG_USERCONFIG is honored as a fallback). A relative path is resolved against the working directory.
stateDir#
- Стандартно:
- Якщо встановлено змінну середовища $XDG_STATE_HOME, тоді $XDG_STATE_HOME/pnpm
- У Windows: ~/AppData/Local/pnpm-state
- On macOS and Linux: ~/.local/state/pnpm
- Тип: path
The directory where pnpm stores machine-level state, including the update checker's pnpm-state.json file.
Since v12.5.0, task concurrency groups also store their shared slot files under stateDir/run-slots. Processes must use the same stateDir to share group limits. Different state directories create independent slot pools, so their combined task count can exceed the configured limit.
Set stateDir in the global configuration file or on the command line. It is ignored in project pnpm-workspace.yaml files.
cacheDir#
- Стандартно:
- Якщо встановлено змінну середовища $XDG_CACHE_HOME, тоді $XDG_CACHE_HOME/pnpm
- У Windows: ~/AppData/Local/pnpm-cache
- В macOS: ~/Library/Caches/pnpm
- У Linux: ~/.cache/pnpm
- Тип: path
Розташування кешу (метадані пакунка, кеш dlx та деякі результати перевірки встановлення).
Так само як і сховище, тека кешу призначена для спільного використання виключно між користувачами, завданнями та процесами, які взаємно довіряють один одному. Якщо ви налаштовуєте спільну cacheDir , забезпечте її захист за допомогою прав доступу до файлової системи, щоб ненадійні користувачі не могли записувати в неї дані.
useStderr#
- Стандартно: false
- Тип: Boolean
Якщо значення true, весь вивід записується у stderr.
updateNotifier#
- Стандартно: true
- Тип: Boolean
Встановіть значення false, щоб приховати сповіщення про оновлення при використанні старішої версії pnpm, ніж остання.
pnpm install and pnpm add check at most once a day, and print how to get the
newer version. The check is skipped in CI and with --offline or
--prefer-offline.
preferSymlinkedExecutables#
- Стандартно: true, коли node-linker встановлено у hoisted і система є POSIX
- Тип: Boolean
Створіть символічні посилання на виконувані файли у node_modules/.bin замість команд shims. Цей параметр ігнорується у Windows, де працюють лише командні shims.
ignoreCompatibilityDb#
- Стандартно: false
- Тип: Boolean
Під час встановлення автоматично виправляються залежності деяких пакунків. Якщо ви хочете вимкнути цей параметр, встановіть для нього значення true.
The patches are applied from Yarn's @yarnpkg/extensions package, plus pnpm's
own curated entries.
Since v12.0.0, the database no longer carries entries that were derived from
static analysis of published packages. Those entries named packages a dependent
imported only for its types. Adding them was at best unnecessary and at worst
broke the dependent: @typescript-eslint/types gained a typescript dependency
resolved to the newest release, which put TypeScript 7 under older
@typescript-eslint versions and made ESLint fail with Cannot read properties of undefined (reading 'Intrinsic').
resolutionMode#
- Default: highest
- Тип: highest, time-based, lowest-direct
Коли resolutionMode встановлено у time-based, залежності буде розвʼязано у такий спосіб:
- Прямі залежності будуть вирішені до найнижчих версій. Отже, якщо у залежностях є
foo@^1.1.0, то буде встановлено1.1.0. - Subdependencies will be resolved from versions that were published no later than one hour after the newest direct dependency. If none of those versions satisfies a subdependency's range, pnpm installs the lowest version that does.
If minimumReleaseAge is also set, pnpm resolves subdependencies against whichever of the two cutoffs is earlier. If no version published before that cutoff satisfies a subdependency's range, pnpm installs the lowest matching version that is older than the minimumReleaseAge cutoff. If every matching version is newer than the minimumReleaseAge cutoff, pnpm falls back to the lowest matching version, and minimumReleaseAgeStrict decides whether pnpm installs it or fails. Only the minimumReleaseAge cutoff decides which versions pnpm reports as too new. A version that is newer than the time-based cutoff but older than the minimumReleaseAge cutoff is installed without a warning or error.
У цьому режимі встановлення з "теплим" кеш відбувається швидше. Це також зменшує ймовірність перехоплення підзалежностей, оскільки підзалежності будуть оновлюватися лише тоді, коли оновлюються прямі залежності.
Цей режим працює лише з повними метаданими npm. Тому в деяких сценаріях це відбувається повільніше. Однак, якщо ви використовуєте Verdaccio v5.15.1 або новішу версію, ви можете встановити параметр registrySupportsTimeField у значення true, і він працюватиме дуже швидко.
Коли resolutionMode встановлено у lowest-direct, прямі залежності буде розвʼязано до їх найнижчих версій.
Only the dependencies declared in package.json count as direct here. A peer dependency that autoInstallPeers adds is not something the project declared, so it is resolved like a subdependency: to the highest version satisfying the peer range, or under time-based, to the highest version within the publish-date cutoff.
registrySupportsTimeField#
- Стандартно: false
- Тип: Boolean
Встановіть значення true, якщо реєстр, який ви використовуєте, повертає поле "time" у скорочених метаданих. Verdaccio supports this from v5.15.1, as do some registry proxies.
This can also be declared per registry, through the supportsTimeField field of a registry declaration. A registry's own declaration wins; this setting is the answer for every registry the project does not describe.
extendNodePath#
- Стандартно: true
- Тип: Boolean
Якщо встановлено значення true, pnpm встановлює змінну середовища NODE_PATH у командних шимах (скрипти-обгортки, створені в теці node_modules/.bin). Якщо значення false, змінна NODE_PATH не встановлена.
Для чого це потрібно#
Ізольована структура node_modules у pnpm означає, що пакунок може отримати доступ лише до своїх власних оголошених залежностей. Однак коли інструмент CLI запускається через командний шим, деякі бібліотеки (зокрема import-local, яку використовують jest, eslint та інші) завантажують модулі з поточної робочої теки, а не з місця розташування самого бінарного файлу. 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.
Щоб усунути цю проблему, pnpm додає до NODE_PATH два типи шляхів:
- 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. - The hoisted
node_modulesdirectory (e.g.,.pnpm/node_modules). This is the directory where hoisted packages are placed whenhoistPatternis set. Node.js не може виявити цю теку за допомогою стандартного алгоритму визначення шляху, тому її потрібно вказати через зміннуNODE_PATH.
NODE_PATH також є важливим, коли увімкнено enableGlobalVirtualStore.
У випадку з глобальним віртуальним сховищем пакунки повʼязуються символічними посиланнями з центральним місцем поза межами проєкту, тому стандартний обхід Node.js вгору по node_modules від фактичного шляху до бінарного файлу не досягне власного node_modules проєкту або його піднятих залежностей. У цьому випадку змінна NODE_PATH повинна містити як кореневу теку проєкту node_modules, так і підняту теку node_modules/.pnpm/node_modules, щоб забезпечити правильне розпізнавання.
Коли слід вимикати#
Ви можете встановити для цього параметра значення false, якщо впевнені, що жоден із інструментів командного рядка у вашому проєкті не використовує модулі з робочої теки і ви не використовуєте глобальне віртуальне сховище. Якщо вимкнути цю функцію, отримаємо дещо простіші командні шими.
deployAllFiles#
- Стандартно: false
- Тип: Boolean
Під час розгортання пакунка або встановлення локального пакунка копіюються всі файли пакунка. Стандартно, якщо пакунок має поле "files" у package.json, то копіюються лише перелічені файли та теки.
embedReadme#
- Стандартно: false
- Тип: Boolean
When set to true, pnpm pack and pnpm publish add the content of the
package's README file to the readme field of the packed package.json, unless
that field is already set. pnpm publish --embed-readme sets it for a single
command.
dedupeDirectDeps#
- Стандартно: false
- Тип: Boolean
Якщо встановлено значення true, залежності, які вже привʼязано до кореневої теки node_modules робочої області, не буде привʼязано до теки node_modules вкладених проєктів.
optimisticRepeatInstall#
- Стандартно: true
- Тип: Boolean
Якщо увімкнено, буде виконано швидку перевірку перед початком інсталяції. Таким чином, повторне встановлення або встановлення в проєкті з усіма оновленнями стає набагато швидшим.
The check compares the manifests, the lockfile, and the patch files by content, so an edit is noticed even when it keeps the file's modification time. A filtered install checks only the selected projects and the workspace projects they depend on.
When the check finds that nothing changed, pnpm skips the install, including the projects' own lifecycle scripts, such as prepare. Set this to false to run those scripts on every install.
requiredScripts#
Scripts listed in this array are required in each project selected by pnpm -r run <script name>. Otherwise, the run fails.
requiredScripts:
- build
enablePrePostScripts#
- Стандартно: true
- Тип: Boolean
Якщо true, pnpm автоматично виконуватиме будь-які пре/пост-скрипти. Отже, виконання pnpm foo буде подібне до виконання pnpm prefoo && pnpm foo && pnpm postfoo.
scriptShell#
- Стандартно: null
- Тип: path
Оболонка для запуску скриптів за допомогою команди pnpm run.
Наприклад, щоб примусово використовувати Git Bash у Windows:
pnpm config set scriptShell "C:\\Program Files\\git\\bin\\bash.exe"
Since v12.4.0, a relative path in pnpm-workspace.yaml resolves from the workspace root, including for scripts that run in a nested package. A bare command name such as bash is still looked up on PATH.
shellEmulator#
- Стандартно: false
- Тип: Boolean
When true, pnpm will use its built-in cross-platform, bash-like shell to
execute scripts.
Цей параметр спрощує написання крос-платформних скриптів. Наприклад, стандартно наступний скрипт не працюватиме в системах, не сумісних з POSIX:
"scripts": {
"test": "NODE_ENV=test node test.js"
}
Але якщо для параметра shellEmulator встановлено значення true, він працюватиме на всіх платформах.
Since v12.8.0, a configured non-empty scriptShell wins over shellEmulator
for pnpm run and lifecycle scripts. The emulator runs only when scriptShell
is unset or empty.
Parameter expansions such as ${MODE:-dev} read the variable when the command runs. For example, export MODE=prod && echo ${MODE:-dev} prints prod.
нотатка
Node.js 22 або вище підтримує виконання скриптів без допомоги pnpm. Для наведеного вище прикладу ви можете запустити скрипт test за допомогою команди node --run test. Однак опція shellEmulator не впливає на це. Скрипти, що залежать від функцій POSIX, повинні виконуватися за допомогою команди pnpm run замість node --run, щоб працювати в середовищах, що не відповідають стандарту POSIX.
catalogMode#
Set catalog.mode alongside catalog.entries to choose how pnpm add uses the default catalog. The top-level catalogMode setting accepts the same values. When a file sets both, catalog.mode wins.
- Стандартно: manual
- Тип: manual, strict, prefer
Керує тим, чи додаються залежності до стандартного каталогу при виконанні pnpm add, і якщо так, то як саме. Є три режими:
- strict — дозволяє лише версії залежностей з каталогу. Додавання залежності за межами діапазону версій каталогу призведе до помилки.
- prefer — надає перевагу версіям з каталогу, але повертається до прямих залежностей, якщо сумісну версію не знайдено.
- manual (стандартно) — не додає автоматично залежності до каталогу.
Since v12.3.0, a specifier that names a location rather than a version is never moved into a catalog: local paths, local tarballs, tarball URLs, and workspace:\<path> ranges stay in the package.json that declares them. Such a specifier is resolved relative to its own project, so one catalog entry could not mean the same directory for every project referencing it.
catalog.defaultSaveTarget#
Set catalog.defaultSaveTarget alongside catalog.entries to choose where pnpm add saves a dependency. Use default for the default catalog or supply a named catalog. The command-line flags --save-catalog and --save-catalog-name take precedence.
catalog:
entries: {}
mode: prefer
defaultSaveTarget: tools
The top-level saveCatalogName setting continues to work. When a file sets both, catalog.defaultSaveTarget wins. If you define the default catalog under catalogs.default, use the top-level settings or move its entries to catalog.entries before using the nested settings.
ci#
- Стандартно: true (коли середовище визначається як CI)
- Тип: Boolean
Цей параметр явно вказує pnpm, чи є поточне середовище середовищем CI (безперервної інтеграції).
In CI, frozenLockfile defaults to true when a lockfile is present, the default reporter is append-only, and the update check is skipped.
This setting is ignored in project pnpm-workspace.yaml files.
catalog.entries and catalog.unused#
Put the default catalog's packages under catalog.entries to configure cleanup alongside them. Use entries: {} for an empty map. Without entries, a key named unused refers to a package.
catalog:
unused: prune
entries:
example-tool: ^2.0.0
catalog.unused accepts ignore (the default) or prune. Pruning covers the default catalog and all named catalogs in catalogs. When a file sets both catalog.unused and catalogPrune, catalog.unused wins.
catalogPrune#
- Стандартно: false
- Тип: Boolean
Якщо встановлено значення 'true', pnpm видалить невикористані записи каталогів під час встановлення.
cleanupUnusedCatalogs — це застарілий варіант назви цього параметра, який продовжує працювати; якщо задано обидва параметри, пріоритет має catalogPrune.
macosBackup.excludeModulesDir#
Added in: v12.6.0
- Стандартно: false
- Тип: Boolean
When set to true on macOS, pnpm marks newly created node_modules, virtual-store, and similar directories with the com.apple.metadata:com_apple_backup_excludeItem extended attribute, so Time Machine skips them.
Set it in the global configuration file or via the PNPM_CONFIG_MACOS_BACKUP_EXCLUDE_MODULES_DIR environment variable. This setting is ignored in project pnpm-workspace.yaml files and on non-macOS platforms.
macosBackup:
excludeModulesDir: true
macosBackup.excludeStoreDir#
Added in: v12.6.0
- Стандартно: false
- Тип: Boolean
When set to true on macOS, pnpm marks newly created package-store directories with the Time Machine exclusion attribute.
Set it in the global configuration file or via the PNPM_CONFIG_MACOS_BACKUP_EXCLUDE_STORE_DIR environment variable. This setting is ignored in project pnpm-workspace.yaml files and on non-macOS platforms.
macosBackup:
excludeStoreDir: true