Gulp.js, watch task runs twice when saving files

后端 未结 12 1169
花落未央
花落未央 2020-12-15 11:03

Given the following piece of code from my gulpfile.js, everytime I save or change a file, the task runs twice instead of one single time, why is that? I just want it to run

相关标签:
12条回答
  • 2020-12-15 11:59

    Hint: the debounce parameter only works for the SAME file/event. If multiple events/files change, it won't help. Sometimes (e.g. I copied files into the a directory being served by my local server) gulp-cached might help, sometimes excluding certain files/patterns (e.g. the sourcemaps files) might help (use ! to negate the selection). e.g.

    gulp.watch(['js/**/*', '!js/**/*.map'])
    
    0 讨论(0)
  • 2020-12-15 12:01

    Aside from editor specific solutions, I wrote a little gulp plugin that solves the problem. You can use gulp-debounce like so:

    npm install --save-dev gulp-debounce

    var debounce = require('gulp-debounce'),
        watch    = require('gulp-watch'),
        through  = require('through2');
    
    gulp.watch('server/**/*.js')
    .pipe(debounce({ wait: 1000 }))
    .pipe(through.obj(function(vinyl) {
      console.log("this won't fire multiple times in 1000ms", vinyl.path);
    });
    
    0 讨论(0)
  • 2020-12-15 12:02

    You should be able to use gulp-batch to batch the changes, since it has a debounce option.

    Something like this:

    gulp.src(['server/**/*.js'], batch({debounce: 50}, function(events) {
        return events
            .pipe(...); // your code here
    }));
    
    0 讨论(0)
  • 2020-12-15 12:04

    I add the same problem in Espresso and you can "fix" it in Gulp by using the debounceDelay option like this :

    gulp.watch('/**/*.less', {debounceDelay: 2000}, ['less']);
    

    That did the trick for me. But it's a pain to add it to every gulp.watch I don't know if we can put this option globaly...

    0 讨论(0)
  • 2020-12-15 12:05

    Seems like the answer to this question is a feature of the editor that was used, Coda 2. Based on some of the comments here and testing with multiple editors, it seems like Coda 2 saves a temporary file or similar and that causes the gulp watch function to be run twice.

    I have not found a viable solution to this when using Coda 2, ended up with switching to Sublime Text 3.

    0 讨论(0)
  • 2020-12-15 12:06

    Had the same issue and it turns out, that gulp-sourcemaps causes it (see -> Using source maps causes task to run twice)

    Get a solution with gulp-notify and the attribute onLast:

    .pipe(notify({message: 'YOUR MESSAGE', onLast: true}));
    
    0 讨论(0)
提交回复
热议问题