I’m trying to figure out how to run my NPM scripts one after another. Here’s what I’ve got in my package.json:
"scripts": {
"say-hi": "echo \"Hey there!\" && exit 1",
"do-stuff": "start cmd.exe @cmd /k \"generate-widget && exit 1\"",
"wrap-up": "start D:\\MyApp\\launchApp",
"say-bye" : "start cmd.exe @cmd /k \"echo \"See ya!\" && exit 1\""
},
I want these to run in order, but when I use pre/post prefixes, they start one after another without waiting for the previous one to finish. Is there a way to make them wait using just NPM? I know Gulp can do this, but I’m hoping to stick with NPM for now. Any ideas would be super helpful!
hey there! have you tried using the &&
operator between your scripts? it runs commands sequentially. like this:
"scripts": {
"run-all": "npm run say-hi && npm run do-stuff && npm run wrap-up && npm run say-bye"
}
This way, each script waits for the previous one to finish before starting. hope this helps!
I’ve dealt with similar issues in my projects. One approach that’s worked well for me is using the npm-run-all
package. It’s a CLI tool that runs multiple npm-scripts in sequence or parallel.
Here’s how you could modify your scripts:
"scripts": {
"say-hi": "echo \"Hey there!\" && exit 1",
"do-stuff": "generate-widget && exit 1",
"wrap-up": "node D:\\MyApp\\launchApp",
"say-bye": "echo \"See ya!\" && exit 1",
"run-all": "npm-run-all say-hi do-stuff wrap-up say-bye"
}
Install npm-run-all with npm install npm-run-all --save-dev
, then run npm run run-all
. This ensures each script completes before the next one starts.
For the do-stuff
and say-bye
scripts, I removed the start cmd.exe @cmd /k
part as it’s usually unnecessary and can cause issues with script sequencing. The wrap-up
script was changed to use node
instead of start
, assuming it’s a Node.js script.
This setup has been reliable in my experience, especially for more complex build processes.
Have you considered using a package like wait-on
? It’s designed for precisely this kind of scenario. Here’s how you could modify your scripts:
"scripts": {
"say-hi": "echo \"Hey there!\" && exit 1",
"do-stuff": "generate-widget && exit 1",
"wrap-up": "node D:\\MyApp\\launchApp",
"say-bye": "echo \"See ya!\" && exit 1",
"run-all": "npm run say-hi && wait-on exit:0 && npm run do-stuff && wait-on exit:0 && npm run wrap-up && wait-on exit:0 && npm run say-bye"
}
Install wait-on
with npm, then run npm run run-all
. This ensures each script completes before the next starts, giving you the sequential execution you’re after. It’s been quite reliable in my projects, especially when dealing with complex build processes or API calls that need to finish before moving on.