Run NPM scripts sequentially but also concurrently
• 1min readShort tutorial on how to run NPM scripts (also compatible with Yarn or pnpm) in parallel while also waiting for other scripts to setup their resources. E.g., imagine a scenario where we start a local web server (Next.js application) and want to automatically kick off our E2E tests (Cypress) as soon as our website is available. Bonus points if we can get both outputs within one terminal window. This is our package.json
for now:
// package.json { ... "scripts" : { "build": "next build", "start": "next start", "build-start": "pnpm build && pnpm start", "e2e:headless": "cypress run", } ... }
In order to solve our problem, we will install two npm packages as dev dependencies: concurrently and wait-on:
pnpm add --save-dev concurrently wait-on
concurrently
is used to run multiple NPM scripts at once while also accumulating their outputs in one terminal windowwait-on
is used to wait for resources to become available, e.g. watching a specific TCP port to open up
After installing the packages, all that’s left for us is to modify our existing E2E script and add one more script to kick off both scripts at once:
// package.json { ... "scripts" : { "build": "next build", "start": "next start", "build-start": "pnpm build && pnpm start", "e2e:headless": "wait-on tcp:3000 && cypress run", "start-e2e": "concurrently --kill-others --kill-others-on-fail --names \"NEXT,CYPRESS\" -c \"bgBlue.bold,bgMagenta.bold\" \"pnpm build-start\" \"pnpm e2e:headless\"" } ... }
Take a look at concurrently’s documentation on how to customize the output style or change behavior.
If we now run pnpm start-e2e
a production build is kicked off and as soon as the web server becomes available, our E2E tests will be run; all done in one terminal window.