首页 > 解决方案 > gulp 4 - 使用监视服务器作业而不是编译器作业

问题描述

如果您有一个开始和完成的任务,则需要在每次文件更改时运行,这里有很好的记录https://gulpjs.com/docs/en/getting-started/watching-files

const { watch } = require('gulp');

exports.default = function() {
  // The task will be executed upon startup
  watch('src/*.js', { ignoreInitial: false }, function(cb) {
    // body omitted
    cb();
  });
};

但是有没有办法像 nodemon 一样使用 gulp watch?您在哪里让任务运行,然后在监视列表中的文件更改时停止并启动它?

- - 更多的 - -

被要求提供一些例子,所以这里有一些不起作用的例子

问题是我不知道如何设置它,以便在触发手表时停止现有服务器。

---- 示例 #1 - 在进程中运行服务器 -----

exports.default = function() {
  watch('src/*.js', { ignoreInitial: false }, function(cb) {
    // this will call back but when the watch is triggered again
    // it will try to start another instance
    app.listen(3000, cb);
  });
};

---- 示例 #2 - 在自己的进程进程中运行服务器 -----

exports.default = function() {
  watch('src/*.js', { ignoreInitial: false }, function(cb) {
    const proc = spawn('node', ['server.js']);
    proc.stdout.pipe(process.stdout);
    proc.stderr.pipe(process.stderr);
    // this will never call the call back
    // so never complete
    cb();
  });
};

标签: gulpgulp-4

解决方案


好吧,至少你可以这样做:

% gulp someTask >/dev/null 2>&1 &
[1] _pid_

如果它是类似的任务,你的 gulp 任务将无限期运行watch

但是这种方法非常肮脏。你应该使用类似的东西nodemon来实现这一点。


推荐阅读