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

package.json

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

Окрім традиційного формату package.json, pnpm також підтримує package.json5 (з допомогою json5) та package.yaml (з допомогою js-yaml).

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.

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

engines.runtime

Додано у: v10.21.0

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

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

Додано у: v10.14

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

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

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

Ви також можете додати кілька середовищ виконання до одного 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. Скрипти використовують локальне середовище виконання, забезпечуючи узгодженість між середовищами.

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.

Оскільки інʼєкційні залежності створюють копії теки з вихідним кодом своєї робочої області, ці копії необхідно якось оновлювати щоразу, коли код модифікується; інакше новий стан не буде відображено для споживачів. 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
  • Тип: 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
}
}