在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,因为我已经在另一个项目中使用了它。


当前回答

简单的节点脚本,让您无需太多麻烦。使用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);
});

其他回答

…但这将在运行wp服务器之前等待开始监视完成。

要使其工作,必须在命令上使用start。其他人已经说明了,但这是它的工作原理,您的代码如下:

“dev”:“npm运行开始监视&&npm运行wp服务器”

应该是:

“dev”:“start npm run start watch&&start npm run-wp server”

这将做的是,它将为每个命令打开一个单独的实例并同时处理它们,就您的初始问题而言,这不应该是一个问题。我为什么这么说?这是因为当您只运行一条语句时,这两个实例都会自动打开,这是您的初始目标。

由于您可能需要向该脚本中添加越来越多的内容,因此它将变得混乱且难以使用。如果您需要检查一些条件和使用的变量,该怎么办?所以我建议您看看允许使用js创建脚本的google/zx。

简单用法:

安装zx:npm i-g zx添加package.json命令(可选,您可以将所有内容移动到脚本中):

  "scripts": {
    "dev": "zx ./scripts/dev.mjs", // run script
    "build:dev": "tsc -w", // compile in watch mode
    "build": "tsc", // compile
    "start": "node dist/index.js", // run
    "start:dev": "nodemon dist/index.js", // run in watch mode
  },

创建dev.mjs脚本文件:

#!/usr/bin/env zx

await $`yarn build`; // prebuild if dist is empty
await Promise.all([$`yarn start:dev`, $`yarn build:dev`]); // run in parallel

现在,每当您想启动开发服务器时,只需运行yarn dev或npm run dev。

它将首先编译ts->js,然后在监视模式下并行运行typescrpt编译器和服务器。当您更改ts文件时->它将由tsc重新编译->nodemon将重新启动服务器。


高级编程使用

加载env变量,在监视模式下编译ts,然后从dist-on-changes(dev.mjs)重新运行服务器:

#!/usr/bin/env zx
import nodemon from "nodemon";
import dotenv from "dotenv";
import path from "path";
import { fileURLToPath } from "url";

// load env variables
loadEnvVariables("../env/.env");

await Promise.all([
  // compile in watch mode (will recompile on changes in .ts files)
  $`tsc -w`,
  // wait for tsc to compile for first time and rerun server on any changes (tsc emited .js files)
  sleep(4000).then(() =>
    nodemon({
      script: "dist/index.js",
    })
  ),
]);

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

function getDirname() {
  return path.dirname(fileURLToPath(import.meta.url));
}

function loadEnvVariables(relativePath) {
  const { error, parsed } = dotenv.config({
    path: path.join(getDirname(), relativePath),
  });

  if (error) {
    throw error;
  }

  return parsed;
}

使用同时调用的包。

npm i concurrently --save-dev

然后按如下方式设置npm run-dev任务:

"dev": "concurrently --kill-others \"npm run start-watch\" \"npm run wp-server\""

我的解决方案类似于Piittis,尽管我在使用Windows时遇到了一些问题。所以我必须验证win32。

const { spawn } = require("child_process");

function logData(data) {
    console.info(`stdout: ${data}`);
}

function runProcess(target) {
    let command = "npm";
    if (process.platform === "win32") {
        command = "npm.cmd"; // I shit you not
    }
    const myProcess = spawn(command, ["run", target]); // npm run server

    myProcess.stdout.on("data", logData);
    myProcess.stderr.on("data", logData);
}

(() => {
    runProcess("server"); // package json script
    runProcess("client");
})();

您还可以在特定脚本上使用pre和post作为前缀。

  "scripts": {
    "predev": "nodemon run-babel index.js &",
    "dev": "webpack-dev-server"
  }

然后运行:npm运行开发