package.json

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

In addition to the traditional package.json format, pnpm also supports package.json5 (in JSON5 format) and package.yaml (in YAML format).

нотатка

pnpm does not read settings from the pnpm field of package.json. Define settings in pnpm-workspace.yaml instead. See Configuring.

bin#

The bin field maps command names to files inside the package. pnpm normalizes backslash separators to / and parent directory segments at the package root. For example, ../dist/cli.js resolves to dist/cli.js inside the package.

engines#

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

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

If the project's engines.pnpm does not accept the running pnpm version, the install fails.

With engineStrict enabled, an incompatible engines.node in the project or in a dependency fails the install. Optional dependencies are exempt. With it disabled, an incompatible engines.node in the project or a required dependency prints a warning.

In a workspace, these checks apply to every workspace project, even when pnpm add or pnpm remove changes only one of them. pnpm run -r and pnpm exec -r run them too, before running anything. A project whose os, cpu, or libc excludes the current platform prints a warning.

A project's engines.node is checked against the first of these that applies:

  1. The nodeVersion setting, when it is set.
  2. The Node.js that pnpm downloads for the project through devEngines.runtime, or through engines.runtime when devEngines.runtime names no Node.js version: the pinned version, or the lowest version of a pinned range.
  3. The root project's runtime pin.
  4. The system Node.js.

--no-runtime skips the two runtime pins.

engines.runtime#

Визначає середовище виконання Node.js, необхідне для залежності. Після оголошення, pnpm автоматично встановить зазначену версію Node.js.

package.json
{
  "engines": {
    "runtime": {
      "name": "node",
      "version": "^24.11.0",
      "onFail": "download"
    }
  }
}

Коли пакунок оголошує середовище виконання:

  1. Для програм CLI: pnpm прив’язує CLI до потрібної версії Node.js, гарантуючи використання правильного середовища виконання незалежно від глобально встановленого екземпляра Node.js.
  2. **Для пакунків зі скриптами postinstall: Скрипт виконується з використанням зазначеної версії Node.js.

Це особливо корисно для залежностей, які потребують певних версій Node.js для коректної роботи.

devEngines.runtime#

Дозволяє вказати один або декілька рушіїв виконання JavaScript, які використовуються в проєкті. Підтримуються рушії Node.js, Deno та Bun.

Наприклад, ось як додати node@^24.4.0 до ваших залежностей:

package.json
{
  "devEngines": {
    "runtime": {
      "name": "node",
      "version": "^24.4.0",
      "onFail": "download"
    }
  }
}

Ви також можете додати кілька середовищ виконання до одного package.json:

package.json
{
  "devEngines": {
    "runtime": [
      {
        "name": "node",
        "version": "^24.4.0",
        "onFail": "download"
      },
      {
        "name": "deno",
        "version": "^2.4.3",
        "onFail": "download"
      }
    ]
  }
}

Як це працює:

  1. pnpm install обробляє вказаний вами діапазон для отримання останньої відповідної версії середовища виконання.
  2. Точна версія (та контрольна сума) зберігається у файлі блокування.
  3. Скрипти використовують локальне середовище виконання, забезпечуючи узгодженість між середовищами.

To override the declared onFail behavior without editing the manifest, use the runtimeOnFail setting.

Since v12.0.0-rc.2, a bare node (or deno/bun) run from inside the project also follows this pin, not just scripts. This can be turned off with the globalShims setting, or skipped for a single command with PNPM_SHIM_BYPASS=1. See project-aware global bins.

packageManager#

Names the project's package manager and its exact version:

package.json
{
  "packageManager": "pnpm@12.0.0"
}

When a command runs with a different pnpm version, pnpm switches to the pinned one, as set by pmOnFail. To allow a range of versions, use devEngines.packageManager. See Package managers for other package managers.

devEngines.packageManager#

Allows specifying the pnpm version via devEngines.packageManager in package.json. Unlike the packageManager field, this supports version ranges. The resolved version is stored in pnpm-lock.yaml under packageManagerDependencies and reused if it still satisfies the range.

When the lockfile records no version yet, pnpm records the running pnpm if it satisfies the range and was published at least minimumReleaseAge ago. Otherwise pnpm records the newest version in the range that is old enough. If no version in the range is old enough, pnpm records the running pnpm.

package.json
{
  "devEngines": {
    "packageManager": {
      "name": "pnpm",
      "version": ">=12.0.0 <13.0.0",
      "onFail": "download"
    }
  }
}

нотатка

When pnpm 12 is declared via the legacy packageManager field and pmOnFail is not set to ignore, its resolution info is written to pnpm-lock.yaml. The lockfile then gains a leading boot document.

Since v12.0.0-rc.6, the field can also name another package manager (npm, yarn or bun), which is what pnpm add npm@11 writes. For those, nothing is recorded in pnpm-lock.yaml: packageManagerDependencies holds pnpm's own pin, and another package manager is pinned in an environment lockfile of its own under the pnpm home.

To override the onFail behavior without editing the manifest, see the pmOnFail setting.

dependenciesMeta#

Додаткова метаінформація, що використовується для залежностей, оголошених всередині dependencies, optionDependencies та devDependencies.

dependenciesMeta.*.injected#

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

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

Наприклад, припустимо, що наступний package.json є пакунком локального робочого простору:

package.json
{
  "name": "card",
  "dependencies": {
    "button": "workspace:1.0.0"
  }
}

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

Але що, якщо button вказує react у своїх peerDependencies? Якщо всі проєкти в монорепо використовують однакову версію react, то проблеми немає. Але що робити, якщо button вимагає card, який використовує react@16 і form, який використовує react@17? Зазвичай вам потрібно вибрати одну версію react і вказати її за допомогою devDependencies з button. Створення символічних посилань не дає можливості задовольнити залежність react різними споживачами, такими як card та form, по-різному.

Поле injected розвʼязує цю проблему, встановлюючи копії button у віртуальному сховищі з жорсткими посиланнями. Щоб досягти цього, package.json для card можна сконфігурувати наступним чином:

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

Тоді як package.json для form можна було б налаштувати наступним чином:

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

З цими змінами ми говоримо, що button є "injected dependency" від card і form. Коли button імпортує react, він перетвориться на react@16 в контексті card, але перетвориться на react@17 в контексті form.

Оскільки інʼєкційні залежності створюють копії теки з вихідним кодом своєї робочої області, ці копії необхідно якось оновлювати щоразу, коли код модифікується; інакше новий стан не буде відображено для споживачів. Якщо ви збираєте декілька проєктів за допомогою команди типу pnpm --recursive run build, це оновлення має відбуватися після того, як буде зібрано кожен пакунок, але до того, як буде зібрано його споживачів. У простих випадках це можна зробити повторним викликом pnpm install, можливо, за допомогою сценарію життєвого циклу package.json, наприклад, "prepare": "pnpm run build" для перезбірки цього проєкту. The syncInjectedDepsAfterScripts setting refreshes the injected copies after the listed scripts run, and while they run. Third party tools such as pnpm-sync and pnpm-sync-dependencies-meta-injected also update injected dependencies, with watch mode support.

peerDependencies#

Peer dependency values are normally semver ranges (^1.0.0), or a workspace: or catalog: specifier.

A peer dependency may also be declared with a specifier that carries a scheme:

package.json
{
  "peerDependencies": {
    "lib-a": "work:5.x.x",
    "lib-b": "npm:other-lib@^5",
    "lib-c": "file:../lib-c",
    "lib-d": "git+https://example.com/lib-d.git"
  }
}

Accepted forms are a named-registry spec (<registry>:<version>), an npm: alias, and a file:, git, or URL spec.

Such a specifier is matched against the semver range it carries: work:5.x.x is checked as 5.x.x and npm:other-lib@^5 as ^5. A specifier that carries no version, such as file:../lib-c, is matched against *, so any version satisfies it. Meanwhile the original specifier is what selects the package when autoInstallPeers installs a missing peer, so the peer is fetched from the aliased name, registry, or source you named.

Bare name@version values are still rejected with ERR_PNPM_INVALID_PEER_DEPENDENCY_SPECIFICATION, as they are almost always a mistake:

package.json
{
  "peerDependencies": {
    "lib-a": "lib-a@1.2.3"
  }
}

peerDependenciesMeta#

У цьому полі перелічено деяку додаткову інформацію, повʼязану із залежностями, переліченими у полі peerDependencies.

peerDependenciesMeta.*.optional#

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

Наприклад:

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

Even though bar was not specified in peerDependencies, it is marked as optional. Таким чином, pnpm буде вважати, що будь-яка версія bar є прийнятною. A missing foo causes no warning either, but an installed foo whose version does not satisfy 1 still produces a peer dependency warning.

publishConfig#

This field carries settings that change how a package is published: registry, access, directory, linkDirectory, executableFiles, and @<scope>:registry. These are preserved in the published package.json.

Additionally, publishConfig can be used to override several other fields in the manifest before the package is packed. Наступні поля можуть бути перевизначені:

Щоб перевизначити поле, додайте версію для публікації до publishConfig.

Наприклад, наступний package.json:

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

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

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

publishConfig.registry#

The registry this package publishes to. It overrides the registry setting, any scope route in registries, and pnpm publish --registry.

package.json
{
  "name": "foo",
  "version": "1.0.0",
  "publishConfig": {
    "registry": "https://registry.npmjs.org/"
  }
}

Only the URL belongs here. pnpm matches it against the auth settings in .npmrc, so the example above publishes with //registry.npmjs.org/:_authToken=....

Each package in a pnpm publish -r run goes to its own target registry, so one command can release a workspace to several registries. --batch then sends one request per registry.

Since v12.7.0, a scoped package can also set its registry under the @<scope>:registry key. For a package in that scope, it takes precedence over publishConfig.registry and over the registry set for the scope in .npmrc:

package.json
{
  "name": "@acme/foo",
  "version": "1.0.0",
  "publishConfig": {
    "@acme:registry": "https://npm.acme.example/"
  }
}

publishConfig.access#

Tells the registry whether the published package should be public or restricted. Same as pnpm publish --access.

Left unset, pnpm sends no access level, so the registry applies its own default and the level of an already published package is left alone. Unscoped packages cannot be restricted.

package.json
{
  "name": "@acme/foo",
  "version": "1.0.0",
  "publishConfig": {
    "access": "public"
  }
}

publishConfig.name#

Publishes the package under a different name than the one its manifest carries in the workspace. This is for a project whose published name is already taken by a sibling project, which otherwise has to be renamed by a build step just before publishing.

package.json
{
  "name": "foo-v2",
  "version": "2.0.0",
  "publishConfig": {
    "name": "foo"
  }
}

Only the published artifact is renamed. Dependents, pnpm-lock.yaml, and release tooling keep addressing the project by its manifest name. The new name reaches the packed manifest, the tarball filename, and everything that addresses the package at the registry: the already-published check of pnpm publish -r, its registry selection, and the release-planning probes of pnpm change status and pnpm version -r.

publishConfig.executableFiles#

Стандартно, з міркувань переносимості, жодні файли, окрім тих, що перелічено у полі bin, не буде позначено як виконувані у результуючому архіві пакунків. Поле executableFiles дозволяє вам оголошувати додаткові поля, які повинні мати прапорець виконуваності (+x), навіть якщо вони не доступні безпосередньо через поле bin.

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

publishConfig.directory#

Ви також можете використовувати поле publishConfig.directory для налаштування опублікованої підтеки відносно поточного package.json.

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

У цьому прикладі тека "dist" повинна містити package.json

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

publishConfig.linkDirectory#

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

Якщо встановлено значення true, під час локальної розробки проєкт буде зʼєднано з текою publishConfig.directory.

Наприклад:

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

publishConfig.variants#

  • Type: Array

Publishes the version as several archives, one per platform, to a registry declared with serverType: pnpr. pnpm installs the archive that fits the host. Each entry describes one archive:

  • targets: the platform tags the archive runs on, such as linux-x64, linux-x64-musl, darwin-arm64-macos_11_0, or win32-x64-napi8. The entry that targets any is the archive of every other host, the one npm and other clients install.
  • files: patterns of the files only this archive holds. Every file no entry claims goes into every archive.
  • manifest: fields that replace the package's fields in this archive's package.json. null removes a field.
package.json
{
  "name": "example-cli",
  "version": "4.0.0",
  "bin": { "example-cli": "bin/example-cli.js" },
  "publishConfig": {
    "variants": [
      { "targets": ["any"], "files": ["lib/**"] },
      {
        "targets": ["linux-x64", "linux-x64-musl"],
        "files": ["native/linux-x64/example-cli"],
        "manifest": { "bin": { "example-cli": "native/linux-x64/example-cli" } }
      }
    ]
  }
}

A platform variant is named by its targets, sorted and joined with +, such as linux-x64+linux-x64-musl. A target appears in one entry only. Without an any entry, the version has no archive for other hosts, and installing it there fails. A platform variant can't run install scripts or have a binding.gyp, and an entry's manifest can't set name, version, or peer dependencies.