每次 Gulpfile 更改后如何重新启动 Gulp?

2022-01-12 00:00:00 node.js workflow javascript gulp gulp-watch

我正在开发一个 Gulpfile.可以让它一改变就重新启动吗?我正在使用 CoffeeScript 开发它.Gulp 是否可以监视 Gulpfile.coffee 以便在保存更改时重新启动?

I am developing a Gulpfile. Can it be made to restart as soon as it changes? I am developing it in CoffeeScript. Can Gulp watch Gulpfile.coffee in order to restart when changes are saved?

推荐答案

您可以创建一个 taskgulp.watch 用于 gulpfile.js 并简单地 spawn 另一个 gulp child_process.

You can create a task that will gulp.watch for gulpfile.js and simply spawn another gulp child_process.

var gulp = require('gulp'),
    argv = require('yargs').argv, // for args parsing
    spawn = require('child_process').spawn;

gulp.task('log', function() {
  console.log('CSSs has been changed');
});

gulp.task('watching-task', function() {
  gulp.watch('*.css', ['log']);
});

gulp.task('auto-reload', function() {
  var p;

  gulp.watch('gulpfile.js', spawnChildren);
  spawnChildren();

  function spawnChildren(e) {
    // kill previous spawned process
    if(p) { p.kill(); }

    // `spawn` a child `gulp` process linked to the parent `stdio`
    p = spawn('gulp', [argv.task], {stdio: 'inherit'});
  }
});

我使用 yargs 来接受主要任务",一旦我们需要重新启动.所以为了运行它,你会调用:

I used yargs in order to accept the 'main task' to run once we need to restart. So in order to run this, you would call:

gulp auto-reload --task watching-task

要进行测试,请调用 touch gulpfile.jstouch a.css 以查看日志.

And to test, call either touch gulpfile.js or touch a.css to see the logs.

相关文章