Chaining and Sequential Scripts
You'll learn how to run multiple npm scripts one after another, creating powerful automated workflows.
The Core Idea
Sometimes you need to run several scripts in a specific order—like building your code, then testing it, then deploying. Instead of running each command manually, you can chain scripts together so they execute sequentially, with each step starting only after the previous one succeeds.
The && Operator
The simplest way to chain scripts is using && (logical AND). This operator only runs the second command if the first one succeeds (exits with code 0):
{
"scripts": {
"build": "webpack --mode production",
"test": "jest",
"deploy": "npm run build && npm run test"
}
}
Running npm run deploy will first build your code. If the build succeeds, it runs tests. If the build fails, testing never happens—preventing you from deploying broken code.
Think of && like a checkpoint system: each task must complete successfully before you move to the next one.
Chaining Multiple Scripts
You can chain as many scripts as needed:
{
"scripts": {
"prepare": "npm run clean && npm run build && npm run test && npm run package"
}
}
Each command waits for the previous one to finish successfully. If any step fails, the entire chain stops immediately.
The npm-run-all Tool
For complex workflows with many scripts, the npm-run-all package offers cleaner syntax and parallel execution options, but for simple sequential chaining, && is built-in and sufficient.
Key Takeaway: Use && to chain npm scripts sequentially, ensuring each step completes successfully before the next one starts—perfect for build, test, and deploy workflows.