在package.json中,我有两个脚本:
"scripts": {
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server",
}
每次开始在Node.js中开发时,我都必须并行运行这两个脚本。我首先想到的是添加第三个脚本,如下所示:
"dev": "npm run start-watch && npm run wp-server"
…但这将在运行wp服务器之前等待开始监视完成。
如何并行运行这些?请记住,我需要查看这些命令的输出。此外,如果您的解决方案涉及构建工具,我宁愿使用gulf而不是gulf,因为我已经在另一个项目中使用了它。
使用npm运行多个并行脚本的分步指南。全局安装npm-run-all包
npm i -g npm-run-all
现在在package.json所在的项目中安装并保存此包
npm i npm-run-all --save-dev
现在以这种方式修改package.json文件中的脚本
"scripts": {
"server": "live-server index.html",
"watch": "node-sass scss/style.scss --watch",
"all": "npm-run-all --parallel server watch"
},
现在运行此命令
npm run all
有关此包的详细信息,请参见给定的链接npm全部运行
简单的节点脚本,让您无需太多麻烦。使用readline组合输出,使行不会被损坏。
const { spawn } = require('child_process');
const readline = require('readline');
[
spawn('npm', ['run', 'start-watch']),
spawn('npm', ['run', 'wp-server'])
].forEach(child => {
readline.createInterface({
input: child.stdout
}).on('line', console.log);
readline.createInterface({
input: child.stderr,
}).on('line', console.log);
});