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

package.json

Файл маніфесту пакунка. Він містить усі метадані пакунка, включно із залежностями, назвою, автором тощо. This is a standard preserved across all major Node.JS package managers, including pnpm.

engines

Ви можете вказати версію Node і pnpm, на якій працює ваше програмне забезпечення:

{
"engines": {
"node": ">=10",
"pnpm": ">=3"
}
}

During local development, pnpm will always fail with an error message if its version does not match the one specified in the engines field.

Unless the user has set the engine-strict config flag (see .npmrc), this field is advisory only and will only produce warnings when your package is installed as a dependency.

dependenciesMeta

Additional meta information used for dependencies declared inside dependencies, optionalDependencies, and devDependencies.

dependenciesMeta.*.injected

If this is set to true for a dependency that is a local workspace package, that package will be installed by creating a hard linked copy in the virtual store (node_modules/.pnpm).

If this is set to false or not set, then the dependency will instead be installed by creating a node_modules symlink that points to the package's source directory in the workspace. Це стандартний спосіб, оскільки він швидший і гарантує, що будь-які зміни в залежності будуть негайно помітні її споживачам.

For example, suppose the following package.json is a local workspace package:

{
"name": "card",
"dependencies": {
"button": "workspace:1.0.0"
}
}

The button dependency will normally be installed by creating a symlink in the node_modules directory of card, pointing to the development directory for button.

But what if button specifies react in its peerDependencies? If all projects in the monorepo use the same version of react, then there is no problem. But what if button is required by card that uses react@16 and form that uses react@17? Normally you'd have to choose a single version of react and specify it using devDependencies of button. Symlinking does not provide a way for the react peer dependency to be satisfied differently by different consumers such as card and form.

The injected field solves this problem by installing a hard linked copies of button in the virtual store. To accomplish this, the package.json of card could be configured as follows:

{
"name": "card",
"dependencies": {
"button": "workspace:1.0.0",
"react": "16"
},
"dependenciesMeta": {
"button": {
"injected": true
}
}
}

Whereas the package.json of form could be configured as follows:

{
"name": "form",
"dependencies": {
"button": "workspace:1.0.0",
"react": "17"
},
"dependenciesMeta": {
"button": {
"injected": true
}
}
}

With these changes, we say that button is an "injected dependency" of card and form. When button imports react, it will resolve to react@16 in the context of card, but resolve to react@17 in the context of form.

Because injected dependencies produce copies of their workspace source directory, these copies must be updated somehow whenever the code is modified; otherwise, the new state will not be reflected for consumers. When building multiple projects with a command such as pnpm --recursive run build, this update must occur after each injected package is rebuilt but before its consumers are rebuilt. For simple use cases, it can be accomplished by invoking pnpm install again, perhaps using a package.json lifecycle script such as "prepare": "pnpm run build" to rebuild that one project. Third party tools such as pnpm-sync and pnpm-sync-dependencies-meta-injected provide a more robust and efficient solution for updating injected dependencies, as well as watch mode support.

peerDependenciesMeta

This field lists some extra information related to the dependencies listed in the peerDependencies field.

peerDependenciesMeta.*.optional

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

Наприклад:

{
"peerDependencies": {
"foo": "1"
},
"peerDependenciesMeta": {
"foo": {
"optional": true
},
"bar": {
"optional": true
}
}
}

Note that even though bar was not specified in peerDependencies, it is marked as optional. Таким чином, pnpm буде вважати, що будь-яка версія bar є прийнятною. However, foo is optional, but only to the required version specification.

publishConfig

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

To override a field, add the publish version of the field to publishConfig.

For instance, the following package.json:

{
"name": "foo",
"version": "1.0.0",
"main": "src/index.ts",
"publishConfig": {
"main": "lib/index.js",
"typings": "lib/index.d.ts"
}
}

Буде опубліковано як:

{
"name": "foo",
"version": "1.0.0",
"main": "lib/index.js",
"typings": "lib/index.d.ts"
}

publishConfig.executableFiles

Стандартно, з міркувань переносимості, жодні файли, окрім тих, що перелічено у полі bin, не буде позначено як виконувані у результуючому архіві пакунків. The executableFiles field lets you declare additional files that must have the executable flag (+x) set even if they aren't directly accessible through the bin field.

{
"publishConfig": {
"executableFiles": [
"./dist/shim.js"
]
}
}

publishConfig.directory

You also can use the field publishConfig.directory to customize the published subdirectory relative to the current package.json.

Очікується, що у зазначеній теці міститиметься модифікована версія поточного пакунка (зазвичай за допомогою сторонніх засобів збирання).

In this example the "dist" folder must contain a package.json

{
"name": "foo",
"version": "1.0.0",
"publishConfig": {
"directory": "dist"
}
}

publishConfig.linkDirectory

  • Default: true
  • Type: Boolean

When set to true, the project will be symlinked from the publishConfig.directory location during local development.

Наприклад:

{
"name": "foo",
"version": "1.0.0",
"publishConfig": {
"directory": "dist",
"linkDirectory": true
}
}

pnpm.overrides

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

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

An example of the "pnpm"."overrides" field:

{
"pnpm": {
"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 $:

{
"dependencies": {
"foo": "^1.0.0"
},
"pnpm": {
"overrides": {
"foo": "$foo"
}
}
}

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

{
"dependencies": {
"foo": "^1.0.0"
},
"pnpm": {
"overrides": {
"bar": "$foo"
}
}
}

Added in: v9.12.0

If you find that your use of a certain package doesn’t require one of its dependencies, you may use - to remove it. For example, if package foo@1.0.0 requires a large package named bar for a function that you don’t use, removing it could reduce install time:

{
"pnpm": {
"overrides": {
"foo@1.0.0>bar": "-"
}
}
}

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

pnpm.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:

{
"pnpm": {
"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:

{
"pnpm": {
"packageExtensions": {
"react-redux@1": {
"peerDependencies": {
"react-dom": "*"
}
}
}
}
}

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

A bigger example:

{
"pnpm": {
"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.

pnpm.peerDependencyRules

pnpm.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:

{
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": ["react"]
}
}
}

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

{
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": ["@babel/*", "@eslint/*"]
}
}
}

pnpm.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:

{
"pnpm": {
"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:

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

pnpm.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. Наприклад:

{
"pnpm": {
"peerDependencyRules": {
"allowAny": ["@babel/*", "eslint"]
}
}
}

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

pnpm.neverBuiltDependencies

This field allows to ignore the builds of specific dependencies. The "preinstall", "install", and "postinstall" scripts of the listed packages will not be executed during installation.

An example of the "pnpm"."neverBuiltDependencies" field:

{
"pnpm": {
"neverBuiltDependencies": ["fsevents", "level"]
}
}

pnpm.onlyBuiltDependencies

A list of package names that are allowed to be executed during installation. If this field exists, only the listed packages will be able to run install scripts.

Приклад:

{
"pnpm": {
"onlyBuiltDependencies": ["fsevents"]
}
}

pnpm.onlyBuiltDependenciesFile

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

Приклад:

{
"dependencies": {
"@my-org/policy": "1.0.0"
},
"pnpm": {
"onlyBuiltDependenciesFile": "node_modules/@my-org/policy/onlyBuiltDependencies.json"
}
}

Сам JSON-файл повинен містити масив імен пакунків:

node_modules/@my-org/policy/onlyBuiltDependencies.json
[
"fsevents"
]

pnpm.allowedDeprecatedVersions

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

Приклад:

{
"pnpm": {
"allowedDeprecatedVersions": {
"express": "1",
"request": "*"
}
}
}

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

pnpm.patchedDependencies

This field is added/updated automatically when you run pnpm patch-commit. Це словник, де ключем має бути назва пакунка та його точна версія. Значення має бути відносним шляхом до файлу виправлення.

Приклад:

{
"pnpm": {
"patchedDependencies": {
"express@4.18.1": "patches/express@4.18.1.patch"
}
}
}

pnpm.allowNonAppliedPatches

When true, installation won't fail if some of the patches from the patchedDependencies field were not applied.

{
"pnpm": {
"patchedDependencies": {
"express@4.18.1": "patches/express@4.18.1.patch"
},
"allowNonAppliedPatches": true
}

pnpm.updateConfig

pnpm.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:

{
"pnpm": {
"updateConfig": {
"ignoreDependencies": ["load-json-file"]
}
}
}

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

pnpm.auditConfig

pnpm.auditConfig.ignoreCves

A list of CVE IDs that will be ignored by the pnpm audit command.

{
"pnpm": {
"auditConfig": {
"ignoreCves": [
"CVE-2022-36313"
]
}
}
}

pnpm.auditConfig.ignoreGhsas

Added in: v9.10.0

A list of GHSA Codes that will be ignored by the pnpm audit command.

{
"pnpm": {
"auditConfig": {
"ignoreGhsas": [
"GHSA-42xw-2xvc-qx8m",
"GHSA-4w2v-q235-vp99",
"GHSA-cph5-m8f7-6c5x",
"GHSA-vh95-rmgr-6w4m"
]
}
}
}

pnpm.requiredScripts

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

{
"pnpm": {
"requiredScripts": ["build"]
}
}

pnpm.supportedArchitectures

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

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

{
"pnpm": {
"supportedArchitectures": {
"os": ["win32"],
"cpu": ["x64"]
}
}
}

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

{
"pnpm": {
"supportedArchitectures": {
"os": ["win32", "darwin", "current"],
"cpu": ["x64", "arm64"]
}
}
}

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

pnpm.ignoredOptionalDependencies

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

{
"pnpm": {
"ignoredOptionalDependencies": ["fsevents", "@esbuild/*"]
}
}

pnpm.executionEnv.nodeVersion

Added in: v9.6.0

Вказує, яку саме версію Node.js слід використовувати для виконання проєкту. pnpm will automatically install the specified version of Node.js and use it for running pnpm run commands or the pnpm node command.

Наприклад:

{
"pnpm": {
"executionEnv": {
"nodeVersion": "16.16.0"
}
}
}

resolutions

Functionally identical to pnpm.overrides, this field is intended to make it easier to migrate from Yarn.

resolutions and pnpm.overrides get merged before package resolution (with pnpm.overrides taking precedence), which can be useful when you're migrating from Yarn and need to tweak a few packages just for pnpm.