Search code examples
gulpgulp-watchbrowser-sync

Gulp: watch HTML files, do some task, then browserSync.reload


Our HTML files are 'assembled' from a few template/partial HTML files. Now I want Gulp to be able to do these tasks sequentially:

  1. Watch 'template' HTML files
  2. If there is any update, run the tasks pages
  3. Then, refresh the webpage.

I read through this tutorial: https://www.browsersync.io/docs/gulp/. But it simply watches the HTML files and reload. I tried this:

gulp.watch([
    path.join(dpw.src.commonLayouts, 'layout.html'),
    dpw.src.commonPages + "/**/*.html",
    dpw.src.sitePages + "/**/*.html"
], ['pages']).on("change", browserSync.reload);

The web page will be reloaded automatically. And the task pages is run.

However, the refreshed page is always one version behind. It means, if I change some text from "12" to be "123", the page is refreshed but the text is "12". Then I change to "1234", the page is refreshed to be "123"...

I am using Gulp 3.9.0 and browser-sync 2.11.1.

Please help. Thanks.


Solution

  • Thanks to @MatthewRath, I implemented it using runSequence:

    gulp.task('pages-watch', function () {
        runSequence('pages', browserSync.reload);
    });
    
    gulp.watch([
        path.join(dpw.src.commonLayouts, 'layout.html'),
        dpw.src.commonPages + "/**/*.html",
        dpw.src.sitePages + "/**/*.html"
    ], ['pages-watch']);
    

    But it introduces a new task, which is a bit tedious.