Introduction to npm-run-all
npm-run-all is a CLI tool that solves an important problem in the JavaScript ecosystem: Managing multiple npm scripts efficiently. Whether you need to run tasks sequentially or in parallel, npm-run-all provides a straightforward API to help streamline your project workflows.
Installation
npm install npm-run-all --save-dev
Basic Commands
Running Scripts Sequentially
You can run scripts in sequence using:
npx run-s script1 script2 script3
Running Scripts in Parallel
To run scripts in parallel, use:
npx run-p script1 script2 script3
Combining Sequential and Parallel Execution
Combine sequential and parallel execution by wrapping parallel scripts in parentheses:
npx run-s script1 (script2 script3) script4
Advanced Usage
Naming npm-run-all Scripts
Inside your package.json
file:
"scripts": {
"lint": "eslint .",
"test": "jest",
"build": "webpack --config webpack.config.js",
"deploy": "npm run lint && npm run test && npm run build"
}
Now, you can run all tasks by simply using:
npx npm-run-all lint test build
Wildcards
Run all matching scripts using wildcards:
npx run-p build:*
Code Snippets
Sequential Task Example
"scripts": {
"clean": "rimraf dist",
"copy-assets": "copyfiles -u 1 src/assets/* dist/assets",
"build-js": "webpack"
}
Run all tasks sequentially:
npx run-s clean copy-assets build-js
Parallel Task Example
"scripts": {
"watch-js": "webpack --watch",
"watch-css": "postcss src/styles --dir src/styles --watch"
}
Run both watchers in parallel:
npx run-p watch-js watch-css
Complex Workflow Example
"scripts": {
"start-server": "node server.js",
"open-browser": "open http://localhost:3000",
"start": "npx run-p start-server open-browser"
}
Example App
An example setup for a simple Node.js application:
{
"name": "example-app",
"version": "1.0.0",
"scripts": {
"clean": "rimraf dist",
"lint": "eslint .",
"test": "jest",
"build": "webpack --config webpack.config.js",
"start-server": "node server.js",
"open-browser": "open http://localhost:3000",
"prestart": "npm-run-all clean lint test build",
"start": "npm-run-all --parallel start-server open-browser"
},
"devDependencies": {
"eslint": "^7.32.0",
"jest": "^26.6.0",
"npm-run-all": "^4.1.5",
"rimraf": "^3.0.0",
"webpack": "^5.52.0"
}
}
This setup ensures a smooth development workflow, cleaning the project, linting the code, running tests, and building the project before starting the server and opening the browser.
Hash: 4d23322e553e9cd37ace0744b4e593dd85d13bf156a5c050fac4c1ba5f87d072