npm scripts — define and run custom commands
Quick Answer
# Run a script
npm run build
npm run dev
npm run test
# Shorthand for built-in scripts (no "run" needed)
npm start
npm test
Usage
Automate project tasks (build, test, lint, deploy) using npm scripts defined in package.json.
Other causes & fixes
Defining scripts in package.json
{
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"test": "vitest run",
"lint": "eslint src --ext ts,tsx"
}
}
Chaining commands
{
"scripts": {
// Run sequentially (stop on failure)
"build": "tsc && vite build",
// Run in parallel
"dev": "tsc -w & vite",
// Cross-platform parallel (use npm-run-all)
"dev2": "run-p tsc:watch vite:serve"
}
}
Passing arguments to a script
npm run test -- --watch
# Everything after -- is forwarded to the script
Pre and post hooks
{
"scripts": {
"prebuild": "rm -rf dist",
"build": "vite build",
"postbuild": "gzip dist/assets/*.js"
}
}
# prebuild runs before build, postbuild runs after
Set environment variables cross-platform
# Install cross-env
npm install --save-dev cross-env
{
"scripts": {
"build:prod": "cross-env NODE_ENV=production vite build"
}
}
Related