Параметри (.npmrc)
pnpm gets its configuration from the command line, environment variables, and
.npmrc files.
The pnpm config command can be used to update and edit the contents of the
user and global .npmrc files.
Ось чотири відповідні файли:
- per-project configuration file (
/path/to/my/project/.npmrc) - per-workspace configuration file (the directory that contains the
pnpm-workspace.yamlfile) - per-user configuration file (
~/.npmrc) - global configuration file (
/etc/npmrc)
All .npmrc files are an INI-formatted list of key = value parameters.
Values in the .npmrc files may contain env variables using the ${NAME} syntax. Змінні 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.
Налаштування підйому залежностей
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.
hoist-workspace-packages
- Default: true
- Type: boolean
When true, packages from the workspaces are symlinked to either <workspace_root>/node_modules/.pnpm/node_modules or to <workspace_root>/node_modules depending on other hoisting settings (hoist-pattern and public-hoist-pattern).
hoist-pattern
- Default: ['*']
- Type: string[]
Tells pnpm which packages should be hoisted to node_modules/.pnpm/node_modules. Стандартно, всі пакунки буде піднято — однак, якщо ви знаєте, що лише деякі пакунки мають фантомні залежності, ви можете скористатися цим параметром, щоб підняти лише фантомні залежності (рекомендується).
Наприклад:
hoist-pattern[]=*eslint*
hoist-pattern[]=*babel*
You may also exclude patterns from hoisting using !.
Наприклад:
hoist-pattern[]=*types*
hoist-pattern[]=!@types/react
public-hoist-pattern
- Default: ['*eslint*', '*prettier*']
- Type: string[]
Unlike hoist-pattern, which hoists dependencies to a hidden modules directory
inside the virtual store, public-hoist-pattern hoists dependencies matching
the pattern to the root modules directory. Підняття до кореневої теки модулів означає, що код застосунку матиме доступ до фантомних залежностей, навіть якщо вони неправильно змінять стратегію розвʼязання.
Цей параметр корисний при роботі з деякими недосконалими інструментами, що підключаються, які не обробляють залежності належним чином.
Наприклад:
public-hoist-pattern[]=*plugin*
Note: Setting shamefully-hoist to true is the same as setting
public-hoist-pattern to *.
You may also exclude patterns from hoisting using !.
Наприклад:
public-hoist-pattern[]=*types*
public-hoist-pattern[]=!@types/react
shamefully-hoist
- Default: false
- Type: 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.
Параметри модулів
modules-dir
- Default: node_modules
- Type: path
The directory in which dependencies will be installed (instead of
node_modules).
node-linker
- Default: isolated
- Type: isolated, hoisted, pnp
Визначає, який компонувальник слід використовувати для встановлення пакунків Node.
- isolated - dependencies are symlinked from a virtual store at
node_modules/.pnpm. - hoisted - a flat
node_moduleswithout symlinks is created. Same as thenode_modulescreated by npm or Yarn Classic. При використанні цього параметра для підйому використовується одна з бібліотек Yarn. Законні причини для використання цього налаштування:- Ваші інструменти погано працюють із символічними посиланнями. A React Native project will most probably only work if you use a hoisted
node_modules. - Ваш проєкт буде розгорнуто на безсерверний хостинг. Деякі безсерверні провайдери (наприклад, AWS Lambda) не підтримують symlinks. Альтернативним розвʼязання цієї проблеми є пакування програми перед розгортанням.
- If you want to publish your package with
"bundledDependencies". - If you are running Node.js with the --preserve-symlinks flag.
- Ваші інструменти погано працюють із символічними посиланнями. A React Native project will most probably only work if you use a hoisted
- pnp - no
node_modules. Plug'n'Play is an innovative strategy for Node that is used by Yarn Berry. It is recommended to also setsymlinksetting tofalsewhen usingpnpas your linker.
symlink
- Default: true
- Type: Boolean
When symlink is set to false, pnpm creates a virtual store directory without
any symlinks. It is a useful setting together with node-linker=pnp.
enable-modules-dir
- Default: true
- Type: 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.
virtual-store-dir
- 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. Кожен проєкт повинен мати власне віртуальне сховище (за винятком робочих просторів, де корінь є спільним).
virtual-store-dir-max-length
Added in: v9.1.0
- Default: 120
- Types: number
Sets the maximum allowed length of directory names inside the virtual store directory (node_modules/.pnpm). Ви можете встановити менше значення, якщо у вас виникають проблеми з довгими шляхами у Windows.
package-import-method
- Default: auto
- Type: auto, hardlink, copy, clone, clone-or-copy
Controls the way packages are imported from the store (if you want to disable symlinks inside node_modules, then you need to change the node-linker setting, not this one).
- 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.
modules-cache-max-age
- Default: 10080 (7 days in minutes)
- Type: number
Час у хвилинах, через який слід видалити порожні пакунки з теки модулів. pnpm зберігає кеш пакунків у теці модулів. Це підвищує швидкість встановлення при перемиканні гілок або пониженню версій залежностей.
dlx-cache-max-age
- Default: 1440 (1 day in minutes)
- Type: number
Час у хвилинах, через який закінчується кеш dlx. Після виконання команди dlx pnpm зберігає кеш, який пропускає крок встановлення для наступних викликів тієї самої команди dlx.
Налаштування сховища
store-dir
- Стандартно:
- 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 копіюватиме пакунки зі сховища, а не звʼязуватиме їх жорсткими посиланнями, оскільки жорсткі посилання можливі лише у тій самій файловій системі.
verify-store-integrity
- Default: true
- Type: 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. If verify-store-integrity is set to false, files in the content-addressable store will not be checked during installation.
use-running-store-server
Застаріла функція
- Default: false
- Type: Boolean
Дозволяє встановлення лише з сервером сховища. Якщо жоден сервер сховища не запущено, інсталяція завершиться невдало.
strict-store-pkg-content-check
Added in: v9.4.0
- Default: true
- Type: Boolean
Деякі реєстри дозволяють публікувати один і той самий контент з різними назвами пакунків та/або версіями. Це порушує перевірку дійсності пакунків у сховищі. To avoid errors when verifying the names and versions of such packages in the store, you may set the strict-store-pkg-content-check setting to false.
Параметри Lockfile
lockfile
- Default: true
- Type: Boolean
When set to false, pnpm won't read or generate a pnpm-lock.yaml file.
prefer-frozen-lockfile
- Default: true
- Type: Boolean
When set to true and the available pnpm-lock.yaml satisfies the
package.json dependencies directive, a headless installation is performed. Встановлення headless пропускає визначення всіх залежностей, оскільки йому не потрібно змінювати файл блокування.
lockfile-include-tarball-url
- Default: false
- Type: Boolean
Add the full URL to the package's tarball to every entry in pnpm-lock.yaml.
git-branch-lockfile
- Default: false
- Type: 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. It is typically used
in conjunction with the command line argument --merge-git-branch-lockfiles or by
setting merge-git-branch-lockfiles-branch-pattern in the .npmrc file.
merge-git-branch-lockfiles-branch-pattern
- 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.
Наприклад:
merge-git-branch-lockfiles-branch-pattern[]=main
merge-git-branch-lockfiles-branch-pattern[]=release*
You may also exclude patterns using !.
peers-suffix-max-length
Added in: v9.3.0
- Default: 1000
- Type: number
Максимальна довжина суфікса ідентифікаторів прямих залежностей, що додається до ключів залежностей у файлі блокування. Якщо суфікс довший, він замінюється хешем.
Registry & Authentication Settings
registry
- Default: https://registry.npmjs.org/
- Type: url
The base URL of the npm package registry (trailing slash included).
<scope>:registry
The npm registry that should be used for packages of the specified scope. For
example, setting @babel:registry=https://example.com/packages/npm/
will enforce that when you use pnpm add @babel/core, or any @babel scoped
package, the package will be fetched from https://example.com/packages/npm
instead of the default registry.
<URL>:_authToken
Define the authentication bearer token to use when accessing the specified registry. Наприклад:
//registry.npmjs.org/:_authToken=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
You may also use an environment variable. Наприклад:
//registry.npmjs.org/:_authToken=${NPM_TOKEN}
Or you may just use an environment variable directly, without changing .npmrc at all:
npm_config_//registry.npmjs.org/:_authToken=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
<URL>:tokenHelper
A token helper is an executable which outputs an auth token. This can be used in situations where the authToken is not a constant value but is something that refreshes regularly, where a script or other tool can use an existing refresh token to obtain a new access token.
The configuration for the path to the helper must be an absolute path, with no arguments. In order to be secure, it is only permitted to set this value in the user .npmrc. Otherwise a project could place a value in a project's local .npmrc and run arbitrary executables.
Setting a token helper for the default registry:
tokenHelper=/home/ivan/token-generator
Setting a token helper for the specified registry:
//registry.corp.com:tokenHelper=/home/ivan/token-generator
Налаштування запиту
ca
- Default: The npm CA certificate
- Type: String, Array or null
Сертифікат підпису центру сертифікації, якому довіряють для SSL-зʼєднань з реєстром. Значення повинні бути у форматі PEM (також відомий як «Base-64 кодований X.509 (.CER)»). Наприклад:
ca="-----BEGIN CERTIFICATE-----\nXXXX\nXXXX\n-----END CERTIFICATE-----"
Встановіть значення null, щоб дозволити довіряти лише відомим реєстраторам, або певному сертифікату ЦС, щоб довіряти лише цьому конкретному центру сертифікації підписів.
Можна довіряти декільком центрам сертифікації, вказавши масив сертифікатів:
ca[]="..."
ca[]="..."
See also the strict-ssl config.
cafile
- Default: null
- Type: path
Шлях до файлу, що містить один або декілька сертифікатів підпису центру сертифікації. Similar to the ca setting, but allows for multiple CAs, as well
as for the CA information to be stored in a file instead of being specified via
CLI.
<URL>:cafile
Define the path to a Certificate Authority file to use when accessing the specified registry. Наприклад:
//registry.npmjs.org/:keyfile=client-cert.pem
cert
- Default: null
- Type: String
Клієнтський сертифікат, який потрібно передати при доступі до реєстру. Значення повинні бути у форматі PEM (також відомий як «Base-64 кодований X.509 (.CER)»). Наприклад:
cert="-----BEGIN CERTIFICATE-----\nXXXX\nXXXX\n-----END CERTIFICATE-----"
It is not the path to a certificate file.
<URL>:certfile
Define the path to a certificate file to use when accessing the specified registry. Наприклад:
//registry.npmjs.org/:certfile=server-cert.pem
key
- Default: null
- Type: String
Ключ клієнта, який потрібно передати при доступі до реєстру. Значення повинні бути у форматі PEM (також відомий як «Base-64 кодований X.509 (.CER)»). Наприклад:
key="-----BEGIN PRIVATE KEY-----\nXXXX\nXXXX\n-----END PRIVATE KEY-----"
It is not the path to a key file (and there is no keyfile option).
Цей параметр містить конфіденційну інформацію. Don't write it to a local .npmrc file committed to the repository.
<URL>:keyfile
Define the path to a client key file to use when accessing the specified registry. Наприклад:
//registry.npmjs.org/:keyfile=server-key.pem
git-shallow-hosts
- Default: ['github.com', 'gist.github.com', 'gitlab.com', 'bitbucket.com', 'bitbucket.org']
- Type: string[]
Під час отримання залежностей, які є Git-репозиторіями, якщо хост вказано у цьому параметрі, pnpm використовуватиме неглибоке клонування, щоб отримати лише потрібний комміт, а не всю історію.
https-proxy
- Default: null
- Type: url
Проксі-сервер для вихідних HTTPS-запитів. If the HTTPS_PROXY, https_proxy,
HTTP_PROXY or http_proxy environment variables are set, their values will be
used instead.
If your proxy URL contains a username and password, make sure to URL-encode them. Наприклад:
https-proxy=https://use%21r:pas%2As@my.proxy:1234/foo
Do not encode the colon (:) between the username and password.
http-proxy
proxy
- Default: null
- Type: url
Проксі для вихідних http-запитів. Якщо встановлено змінні оточення HTTP_PROXY або http_proxy, налаштування проксі будуть враховані базовою бібліотекою запитів.
local-address
- Default: undefined
- Type: IP Address
IP-адреса локального інтерфейсу для підключення до реєстру npm.
maxsockets
- Default: network-concurrency x 3
- Type: Number
Максимальна кількість зʼєднань, які можна використовувати для одного джерела (комбінація протокол/хост/порт).
noproxy
- Default: null
- Type: String
Розділений комами рядок розширень доменів, для яких не слід використовувати проксі-сервер.
strict-ssl
- Default: true
- Type: Boolean
Чи потрібно робити перевірку SSL-ключів при запитах до реєстру через HTTPS.
See also the ca option.
network-concurrency
- Default: 16
- Type: Number
Контролює максимальну кількість запитів HTTP(S) для одночасної обробки.
fetch-retries
- Default: 2
- Type: Number
Скільки разів повторити спробу, якщо pnpm не вдається отримати дані з реєстру.
fetch-retry-factor
- Default: 10
- Type: Number
Експоненціальний коефіцієнт для повторної спроби.
fetch-retry-mintimeout
- Default: 10000 (10 seconds)
- Type: Number
Мінімальний (базовий) тайм-аут для повторних запитів.
fetch-retry-maxtimeout
- Default: 60000 (1 minute)
- Type: Number
Максимальний таймаут очікування, щоб гарантувати, що фактор повторних спроб не робить запити занадто довгими.
fetch-timeout
- Default: 60000 (1 minute)
- Type: Number
Максимальний час очікування виконання HTTP-запитів.
Параметри прямих залежностей
auto-install-peers
- Default: true
- Type: 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.
Розвʼязання конфліктів
У випадку конфлікту версій вам потрібно буде визначити, яку версію прямої залежності встановити самостійно, або оновити залежності, щоб узгодити їхні вимоги до прямих залежностей.
dedupe-peer-dependents
- Default: true
- Type: 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. Therefore, you may now use the dedupe-peer-dependents setting to deduplicate webpack when it has no conflicting peer dependencies (explanation at the end). In this case, if we set dedupe-peer-dependents to true, both projects will use the same webpack instance, which is the one that has esbuild resolved:
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.
strict-peer-dependencies
- Default: false
- Type: Boolean
Якщо цей параметр увімкнено, команди не будуть виконуватися, якщо у дереві відсутня або невірна залежність від прямої залежності.
resolve-peers-from-workspace-root
- Default: true
- Type: Boolean
Якщо увімкнено, залежності кореневого проєкту робочої області використовуються для розвʼязання прямих залежностей будь-яких проєктів у робочій області. Це корисна функція, оскільки ви можете встановлювати прямі залежності лише у корені робочого простору, і ви можете бути впевнені, що всі проєкти у робочому просторі використовують однакові версії прямих залежностей.
Параметри 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
--colorflag 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.
use-beta-cli
- Default: false
- Type: Boolean
Експериментальна опція, яка дозволяє використовувати бета-функції CLI. Це означає, що ви можете отримати деякі зміни у функціоналі CLI, які є порушеннями або потенційними помилками.
recursive-install
- Default: true
- Type: 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.
engine-strict
- Default: false
- Type: 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.
npm-path
- Type: path
Розташування бінарного файлу npm, який pnpm використовує для деяких дій, таких як публікація.
package-manager-strict
- Default: true
- Type: 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.
package-manager-strict-version
Added in: v9.2.0
- Default: false
- Type: Boolean
When enabled, pnpm will fail if its version doesn't exactly match the version specified in the packageManager field of package.json.
manage-package-manager-versions
Added in: v9.7.0
- Default: false
- Type: 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"
}