Front-end projects often include multiple NPM scripts. Sometimes multiple commands need to be serialized, that is, scripts follow a strict execution order. Sometimes you need to parallel them to speed things up,
Serial execution (synchronization) &&
"test": "npm run lint:js && npm run lint:css && npm run lint:json && npm run lint:markdown && mocha tests/"
Copy the code
Parallel execution (asynchronous) &
"test": "npm run lint:js & npm run lint:css & npm run lint:json & npm run lint:markdown & mocha tests/"
Copy the code
& wait
The added benefit of wait is that if we start a long-running process in any subcommand, such as mocha’s –watch configuration enabled, we can use CTRL + C to terminate the process, but if we don’t, there is no way to terminate the process that started in the background.
npm run lint:js & npm run lint:css & npm run lint:json & npm run lint:markdown & mocha tests/ & wait
Copy the code
npm-run-all
annotation
"test": "# Run all code checks and unit tests \n npm-run-all --parallel Lint :* mocha"
Copy the code
NPM Script hooks (Lifecycle mechanisms)
The pre and post
When running NPM run test, there are three phases:
1. Check whether the pretest command exists in the scripts object. If yes, run the pretest command.
2. Check whether the test command exists. If yes, run the test command.
3. Check whether the posttest command exists. If yes, run the posttest command.
Cross-platform NPM script
Rimraf, or del-cli, is used to delete files and directories, implementing functions similar to RM -rf;
CPR, used to copy and copy files and directories, to achieve functions similar to CP-R;
Make-dir -cli is used to create a directory. The function is similar to mkdir -p.
With install onchange, NPM script is automatically run when files change
npm i onchange -D
npm install onchange --save-dev
yarn add onchange -D
Copy the code
"watch": "npm-run-all --parallel watch:*"."watch:lint": "onchange -i \"**/*.js\" \"**/*.less\" -- npm run lint"."watch:test": "npm t -- --watch".Copy the code
Use Livereload for automatic refresh
It is the ancestor of automatic refresh technology, the subsequent HMR, HR and so on are its improved version
Execute NPM script in Git Hooks
Git has Hooks that allow you to do what you want before committing or after pushing your code
Git uses –no-verify (-n) to skip local checks