pnpm run

Алиасы: run-script

Запускает скрипт, определенный в файле манифеста пакета.

Примеры#

Допустим, у вас есть сценарий watch, настроенный в файле package.json, например:

"scripts": {
    "watch": "webpack --watch"
}

Теперь вы можете запустить этот сценарий с помощью pnpm run watch! Просто, правда? Для тех, кто любит сохранять нажатия клавиш и время, хорошая новость: все сценарии получают алиас в виде команд pnpm, поэтому, в конечном счете, pnpm watch - это всего лишь краткая запись для pnpm run watch (ТОЛЬКО для сценариев, которые не используют то же имя, что и уже существующие команды pnpm).

Выполнение нескольких сценариев#

Вы можете запускать несколько сценариев одновременно, используя регулярное выражение, а не имя сценария.

pnpm run "/<regex>/"

Запустить все скрипты, названия которых начинаются с watch::

pnpm run "/^watch:.*/"

The selector must be written as a regular expression literal — that is, wrapped in slashes — and quoted, so the shell does not mangle it. A plain string is always treated as a literal script name, and a script whose name matches the argument exactly takes precedence over regex matching.

Matching is not anchored, so "/build:.*/" also matches prebuild:web. Anchor the pattern with ^ and $ when you need an exact prefix.

Matched scripts run in lexicographical order, so the selection is deterministic regardless of the order the scripts appear in package.json. To run them strictly one at a time, add --sequential.

Regular expression flags are not supported: pnpm run "/^build:.*/i" fails with ERR_PNPM_UNSUPPORTED_SCRIPT_COMMAND_FORMAT.

Подробности#

В дополнение к уже существующим в окружении PATH, pnpm run содержит node_modules/.bin в PATH, предоставляемом сценариям. Это значит, до тех пор, пока у вас установлен пакет, вы можете использовать его в скрипте, как обычную команду. Например, если у вас установлен eslint, вы можете создать такой сценарий:

"lint": "eslint src --fix"

И, хотя в вашей оболочке не установлен eslint, он будет работать.

Для рабочих областей, <workspace root>/node_modules/.bin также добавляется в PATH, поэтому если инструмент установлен в корне рабочей области, он может называться в сценариях любого пакета.

Окружение#

Есть некоторые переменные окружения, которые pnpm автоматически создает для исполняемых сценариев. Эти переменные окружения могут использоваться для получения контекстной информации о запущенном процессе.

Это переменные окружения, созданные pnpm:

  • npm_command - содержит имя исполняемой команды. При исполнении команды pnpm run значение этой переменной будет "run-script".

Опции#

Любые параметры команды run должны быть перечислены перед названием сценария. Опции, перечисленные после имени скрипта передаются исполняемому скрипту.

Все они будут запускать pnpm CLI с параметром --silent:

pnpm run --silent watch
pnpm --silent run watch
pnpm --silent watch

Все аргументы после имени команды добавляются в исполняемый сценарий. Так что, если watch запускает webpack --watch, то эта команда:

pnpm run watch --no-color

запустит:

webpack --watch --no-color

--recursive, -r#

This runs an arbitrary command from each package's "scripts" object. If a package doesn't have the command, it is skipped. If none of the packages have the command, the command fails.

--if-present#

You can use the --if-present flag to avoid exiting with a non-zero exit code when the script is undefined. This lets you run potentially undefined scripts without breaking the execution chain.

--no-bail#

Continue running the remaining matched scripts even if one of them fails. The command still exits with a non-zero exit code if any script failed.

--parallel#

Полностью игнорирует параллелизм и топологическую сортировку, запуская заданный скрипт немедленно во всех подходящих пакетах с префиксом потокового вывода. Это предпочтительный флаг для долго выполняющихся процессов над многими пакетами, например, для длительного процесса сборки.

--sequential, -s#

Added in: v11.14.0

Run the selected scripts one by one. This forces --workspace-concurrency to 1, so scripts matched by a regex selector never overlap — neither across workspace packages nor within a single package.

pnpm run --sequential "/^build:.*/"

In a recursive run this serializes scripts across workspace projects as well as within each one. --sequential takes precedence over --parallel: concurrency is pinned to 1 whenever it is set, regardless of the order the two flags appear in.

заметка

For pnpm run, -s is the shorthand for --sequential. Everywhere else in the CLI, -s remains the shorthand for --reporter=silent. The long form --silent is unaffected in all commands.

--stream#

Stream output from child processes immediately, prefixed with the originating package directory. This allows output from different packages to be interleaved.

--aggregate-output#

Aggregate output from child processes that are run in parallel, and only print output when the child process is finished. Это делает чтение больших лог-файлов после запуска pnpm -r <command> с --parallel или --workspace concurrency=<number> гораздо проще (особенно при использовании CI). Only --reporter=append-only is supported.

--resume-from <package_name>#

Возобновление выполнения из конкретного проекта. This can be useful if you are working with a large workspace and you want to restart a build at a particular project without running through all of the projects that precede it in the build order.

--report-summary#

Record the result of the scripts executions into a pnpm-exec-summary.json file.

An example of a pnpm-exec-summary.json file:

{
  "executionStatus": {
    "/Users/zoltan/src/pnpm/pnpm/cli/command": {
      "status": "passed",
      "duration": 1861.143042
    },
    "/Users/zoltan/src/pnpm/pnpm/cli/common-cli-options-help": {
      "status": "passed",
      "duration": 1865.914958
    }
  }

Possible values of status are: 'passed', 'queued', 'running'.

--reporter-hide-prefix#

Hide workspace prefix from output from child processes that are run in parallel, and only print the raw output. This can be useful if you are running on CI and the output must be in a specific format without any prefixes (e.g. GitHub Actions annotations). Only --reporter=append-only is supported.

--filter <селектор пакета>#

Подробнее о фильтрации.

pnpm-workspace.yaml settings#

enablePrePostScripts#

  • Default: true
  • Type: Boolean

When true, pnpm will run any pre/post scripts automatically. So running pnpm foo will be like running pnpm prefoo && pnpm foo && pnpm postfoo.

scriptShell#

  • Default: null
  • Type: path

The shell to use for scripts run with the pnpm run command.

For instance, to force usage of Git Bash on Windows:

pnpm config set scriptShell "C:\\Program Files\\git\\bin\\bash.exe"

shellEmulator#

  • Default: false
  • Type: Boolean

When true, pnpm will use a JavaScript implementation of a bash-like shell to execute scripts.

This option simplifies cross-platform scripting. For instance, by default, the next script will fail on non-POSIX-compliant systems:

"scripts": {
  "test": "NODE_ENV=test node test.js"
}

But if the shellEmulator setting is set to true, it will work on all platforms.

заметка

Node.js 22 or higher supports running scripts without pnpm's assistance. For the example above, you can run the test script with node --run test. However, the shellEmulator option has no effect on this. Scripts that depend on POSIX features are required to be run pnpm run instead of node --run to work in non-POSIX-compliant environments.