Skip to content
jshacks.dev
Packages

Run a package script with npm run

Run a package.json script with npm run, see how pre and post hooks fire around it, and use the silent flag to hide npm's own output.

1 min read
Summarize in AI

A script is a named shell command in package.json. npm run adds node_modules/.bin to the path, so local tools work without npx.

package.jsonJSON
{
  "scripts": {
    "prebuild": "echo cleaning",
    "build": "echo building",
    "postbuild": "echo done"
  }
}
Shell
npm run build
Text
> [email protected] prebuild
> echo cleaning

cleaning

> [email protected] build
> echo building

building

> [email protected] postbuild
> echo done

done

Naming a script with the pre or post prefix makes npm run it before or after the script of that name. The lines starting with > are npm's own; npm run build --silent removes them, which helps when you pipe the output elsewhere. See [npm's run-script docs](https://docs.npmjs.com/cli/v10/commands/npm-run-script).

test, start and stop have shortcuts: npm test and npm start skip the word run. A failing command stops the chain, and npm exits with its code. Scripts use sh on macOS and Linux and cmd.exe on Windows, so avoid shell-specific syntax if people on Windows work on the project.

Taggednpm
Share

More snippets

Packages

Initialize a package with npm init

Initialize a package.json with npm init, skip the questions with the yes flag, and set your own defaults for author and license in npm config.

1 min read
Packages

Generate a changelog from commits

Turn conventional commit messages into a CHANGELOG.md section with conventional-changelog, grouped by feature and fix. Works with any Git history.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.