Explain Codes LogoExplain Codes Logo

Running NPM scripts sequentially

javascript
npm-scripts
task-sequencing
package-json
Nikita BarsukovbyNikita BarsukovยทMar 5, 2025
โšกTLDR

Use && to execute npm scripts consecutively inside your package.json file.

"scripts": { "start": "npm run script1 && npm run script2 // script2 never runs until script1 is done, they respect each other's space ๐Ÿ‘" }

To run them, use npm run start; script1 executes first, and after successful completion, script2 begins.

This pattern is primordial for running tasks (like setup, build, and test) where each step depends on the successful completion of the prior one.

Streamlining with npm-run-all

Instead of typing myriad && characters, the npm-run-all package makes things a lot easier and cleaner:

"scripts": { "start": "run-s script1 script2 // Looks cleaner, works even better ๐Ÿงน" }

Implicit chaining with pre/post hooks

NPM allows you to chain tasks without specifying && by using pre/post hooks. Scripts prefixed with pre and post run before and after the main script, respectively, keeping your package.json lean:

"scripts": { "prebuild": "npm run clean", "build": "npm run compile", "postbuild": "npm run test" }

In this case, running npm run build will trigger clean, compile, and test in an ordered sequence.

Handling scripts' exit codes

Ensure careful handling of exit codes in scripts. Nonzero exit codes will cease the chain โ€“ a handy feature if you want tasks to halt upon encountering an error.

Advanced task sequencing

If your workflows are complex, consider using Node.js child processes or task runners like Gulp:

  • Node.js provides child_process.spawn() or child_process.exec() for cases you need a higher degree of control over process execution.
  • Tools like Gulp offer additional mechanisms to manage task dependencies and sequencing.

Ensuring cross-platform compatibility

To avoid compatibility issues across different OS', consider using tools such as cross-env, especially for managing environment variables in npm-scripts.

Situational applications for sequential execution

  • Continuous integration: Ensures tests are run only once the build process is complete.
  • Deployment: Affirms database migrations are run after the server starts up but before the app is launched.
  • Development setup: Guarantees dependencies are installed before starting the local development servers.