npm scripts and lifecycle hooks

Beginner · 3 min

Defining and running scripts, pre and post hooks, passing arguments, npx and npm exec, running across workspaces, and how node --run differs.

Before thispackage.json fields and exports

Codevolution · 3 min

npm scripts and lifecycle hooks

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Each entry in the `scripts` field is a shell command you run with `npm run <name>`. `test`, `start`, `stop` and `restart` also have shorthands (`npm test`, `npm start`).
  • npm runs a script named `pre<name>` before and `post<name>` after any script `<name>`, automatically. `npm test` runs `pretest`, `test`, `posttest`. Running with `--ignore-scripts` skips those hooks.
  • Arguments go after `--`: `npm run build -- --prod` appends `--prod` to the script's command. Without the `--`, npm would try to read the flag itself.
  • npm puts `node_modules/.bin` on `PATH` while a script runs, so a locally installed tool such as `eslint` can be called by name without installing it globally.
  • `npx <tool>` (the same as `npm exec <tool>`) runs a package's binary, using the local copy if installed and offering to download it otherwise. `npm run <name> --workspaces --if-present` runs a script in every workspace that defines it.

Scripts are named shell commands

Every project has a few commands people run repeatedly: build, test, lint, start the dev server. Written in a README they drift out of date and differ between machines. npm’s answer is to store them in package.json, under the name everyone runs them by:

{
  "scripts": {
    "start": "node server.js",
    "build": "tsc -p .",
    "lint": "eslint .",
    "test": "node --test"
  }
}

npm run build runs tsc -p . in the project directory. npm test and npm start have shorthands because they are so common (npm run test and npm run start also work), and npm run with no name lists every script in the project.

A script is a command for your platform’s shell, so &&, pipes and environment variables work, but differ between Windows and Unix. For cross-platform needs, either keep a script as node something.js or use a small tool; the Node scripts above are portable.

Pre and post hooks

For any script named x, npm automatically runs prex before it and postx after it:

{
  "scripts": {
    "prebuild": "echo [prebuild]",
    "build": "echo [build]",
    "postbuild": "echo [postbuild]"
  }
}

npm run build prints [prebuild], [build], [postbuild] in that order, and npm test runs pretest first. A non-zero exit in any step stops the chain. Use prebuild to clean the output folder and pretest to build the code under test, so that running one command always does the right thing.

Some scripts have special meaning around installing and publishing. prepare runs after a plain npm install in a project and before publishing, which is where people build or install git hooks. prepack runs before the tarball is made, and prepublishOnly runs only before npm publish. In a test, npm pack ran the prepack script before listing the package contents. Scripts named preinstall, install and postinstall run when someone installs your package as a dependency. That is powerful and risky, and the topic of securing Node dependencies. npm run build --ignore-scripts skips the hooks.

Passing arguments

Anything you add after -- goes to the script, not to npm:

npm run build -- --prod      # runs: echo [build] args: --prod

Without the --, npm would try to interpret --prod itself. Inside the script, npm also sets environment variables such as npm_lifecycle_event (the script’s name), npm_package_name and npm_package_version:

{ "scripts": { "env": "node -p \"[process.env.npm_lifecycle_event, process.env.npm_package_name].join(' | ')\"" } }

npm run env printed env | demo in a test on npm 11.20. Reading your own version this way is fine; do not depend on npm injecting every package.json field as a variable.

The local bin folder

While a script runs, npm adds ./node_modules/.bin to the front of PATH. A dependency that provides a command, such as eslint, tsc or vitest, can be called by name in a script, with the exact version the project pinned. This is why tools belong in devDependencies rather than being installed globally: the same script then works on every machine and in CI.

npx and npm exec

npx and npm exec run a package’s binary. They use the project’s local copy if it is installed, and otherwise offer to download the package for this one run:

npx tsc --version        # local TypeScript if present
npm exec -- node -p 1    # prints 1; the -- separates npm's flags from the command

Downloading and running code on demand is convenient and is also running code from the internet, so be careful with names you have not checked.

Workspaces

In a monorepo, run a script across the workspaces with:

npm run test --workspaces --if-present     # every workspace that defines "test"
npm run start --workspace=@mono/app        # just one

--if-present skips workspaces without that script instead of failing. See npm workspaces and monorepos.

node –run

Node can run a scripts entry directly: node --run build. It skips npm’s startup, so it is faster. Tested on Node 26.13.1: node_modules/.bin is on PATH and arguments after the script name are passed along, but pre/post hooks do not run and workspace flags are not supported. Use it for hot, simple scripts and npm run when you rely on hooks. Running code and the CLI covers the rest of node’s own flags.

What the video covers

Codevolution’s three-minute video introduces defining and running npm scripts from package.json. At that length it is an introduction only, so hooks, argument passing, npx and workspaces come from the prose, each checked by running them against npm 11.20 and Node 26.13.1. No transcript was available. Steve Griffith’s longer tour under “go deeper” also covers running scripts with arguments. Both are from before node --run existed in its current form.

Where this fits

Scripts tie the tooling of a project together. Next, npm workspaces and monorepos scales one package.json to many. For the front-end tooling most scripts invoke, see module bundlers and build tools.

Check yourself

  1. 01You define `"build"`, `"prebuild"` and `"postbuild"` scripts and run `npm run build`. In what order do they run?

    `prebuild`, then `build`, then `postbuild`. npm looks for `pre` and `post` versions of whatever script you run and chains them. If a step exits with a non-zero code, the chain stops there.

  2. 02How do you pass `--watch` through to the command behind `npm run test`?

    `npm run test -- --watch`. The `--` tells npm to stop reading flags and append everything after it to the script's command. `npm test -- --watch` works the same way.

  3. 03Your script calls `eslint .` and works for you, but fails on a clean CI machine with `eslint: not found`. What is the likely cause?

    `eslint` was installed globally on your machine instead of being a `devDependency`. When a script runs under npm, `node_modules/.bin` is on the `PATH`, so a local install is found by name. Add it with `npm install -D eslint`.

  4. 04What do you give up by using `node --run build` instead of `npm run build`?

    The `pre` and `post` hooks do not run, and you lose npm-specific features such as workspace flags. In exchange, it skips starting npm, so it is faster. It does still put `node_modules/.bin` on `PATH`.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark