npm Scripts
Define named commands in package.json and run them with npm run.
Syntax
npm run <script-name>The scripts field in package.json lets you name common commands. Run them with npm run <name>.
Special names
A few script names have shortcuts — start and test can be run as npm start and npm test (no run needed).
Scripts keep long commands in one place, so the whole team runs them the same way.
Example
{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "node --test",
"lint": "eslint ."
}
}
// Run with: npm start npm run dev npm testWhen to use it
- A team standardises on `npm run build` across all projects so any developer or CI system can build the app without knowing the underlying tool chain.
- A `pretest` script automatically lints and type-checks the codebase before Jest runs, catching syntax errors before slow tests start.
- A release engineer uses `npm run release` which is a single script that bumps the version, builds, and publishes to npm in sequence.
More examples
Define and run scripts
Defines five common scripts in `package.json` that run with `npm run <name>` (or just `npm start`/`npm test`).
{
"scripts": {
"start": "node src/index.js",
"dev": "node --watch src/index.js",
"build": "tsc --outDir dist",
"test": "jest --coverage",
"lint": "eslint src"
}
}Pre and post hooks
Uses `pre` and `post` hooks -- npm runs `pretest` automatically before `test` and `posttest` after it.
{
"scripts": {
"pretest": "eslint src",
"test": "jest",
"posttest": "echo 'Tests complete'"
}
}Chain commands and pass args
Passes extra arguments to a script with `--` and chains scripts with `&&` for sequential execution.
# Run test and pass extra flags to jest:
npm test -- --testPathPattern=auth
# Chain two scripts sequentially:
# In package.json: "ci": "npm run lint && npm test"
npm run ci
Discussion