Search code examples
javascriptnpmgulpwatchify

gulp watchify needs two saves to include changes


Been trying to use watchify for a while now and I have a problem with the saving.

It seems like for every change I make, I need to save two times in order for the changes to be applied in the output.

If I add code in any js-file, the newly added code will only show up if the task runs two times.

My code for the mainScrpits-task

var customOpts = {
      entries: ['./app/app.js'],
      debug: true
    };
    var opts = assign({}, watchify.args, customOpts);
    var b = watchify(browserify(opts));


    gulp.task('mainScripts', bundle);
    b.on('update', bundle);
    b.on('log', gutil.log);

    function bundle() {
      console.log('bundle');
      return b.bundle()
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(source('main.js'))
        .pipe(buffer())
        .pipe(gulpif(!condition, sourcemaps.init({
          loadMaps: true
        })))
        .pipe(gulpif(!condition, sourcemaps.write('./')))
        .pipe(gulp.dest('./dist/js/'))
        .pipe(gulpif(isLocal(), connect.reload()));
    }

The "watch"-task

gulp.task('watch', function() {
  gulp.watch('app/**/*.js', ['mainScripts']);
});

Solution

  • Both watchify and gulp.watch are looking for changes on your files and that causes race conditions on the creation of the bundle.

    Your watch task should just start your mainScripts task:

    gulp.task('watch', function() {
      gulp.start('mainScripts');
    });