自我重装gulp上的重复任务

时间:2015-04-08 15:36:56

标签: gulp gulp-watch

我已经设置了gulp,以便在修改gulpfile时重新加载。这个基本过程正在发挥作用,但由于某种原因,旧任务似乎没有被正确终止。

var gulp = require('gulp');
var less = require('gulp-less');
var spawn = require('child_process').spawn;

gulp.task('default', function(){
    var p;

    if(p)
        p.kill();

    p = spawn('gulp', ['watch'], {stdio: 'inherit'});
});

gulp.task('watch', ['styles', 'watch-styles', 'watch-gulp']);

gulp.task('styles', function(){
    return gulp.src('./**/*.less')
    .pipe(less())
    .pipe(gulp.dest('./'))
});

gulp.task('watch-styles', ['styles'], function(){
    gulp.watch('./**/*.less', ['styles']);
});

gulp.task('watch-gulp', ['styles'], function(){
  gulp.watch('./gulpfile.js', ['default']);
});

这是一个演示问题的基本gulp文件。当我调整gulpfile以使其重新加载时,我会在控制台中收到它:

[11:21:02] Starting 'default'...
[11:21:02] Finished 'default' after 5.25 ms
[11:21:02] Using gulpfile ~/repo/gulp-reload/gulpfile.js
[11:21:02] Starting 'styles'...
[11:21:02] Finished 'styles' after 34 ms
[11:21:02] Starting 'watch-styles'...
[11:21:03] Finished 'watch-styles' after 669 ms
[11:21:03] Starting 'watch-gulp'...
[11:21:03] Finished 'watch-gulp' after 1.83 ms
[11:21:03] Starting 'watch'...
[11:21:03] Finished 'watch' after 2.92 μs

然后修改目录中的less文件会产生此输出

[11:21:24] Starting 'styles'...
[11:21:24] Finished 'styles' after 8.95 ms
[11:21:24] Starting 'styles'...
[11:21:24] Finished 'styles' after 2.92 ms

每次后续重启似乎都会导致对样式的额外调用,就像老观察者仍在那里一样。

我也在这个示例项目中创建了一个小repo on Github

1 个答案:

答案 0 :(得分:0)

在此任务中:

gulp.task('default', function(){
    var p;

    if(p)
        p.kill();

    p = spawn('gulp', ['watch'], {stdio: 'inherit'});
});

永远不会定义p,因为在调用该函数时总是会创建一个新变量。此外,您没有指向您想要杀死的进程的指针。更安全的方法是手动结束所有其他观察者:

gulp.task('watch-styles', ['styles'], function(){
    var watcher = gulp.watch('./**/*.less', ['styles']);
    watchers.push(watcher);
});

gulp.task('watch-gulp', ['styles'], function(){
    var watcher = gulp.watch('./gulpfile.js', ['default']);
    watchers.push(watcher);
    watcher.on('change', function(){
        watchers.forEach(function(el){
            el.end();
        })
    })
});