How I resolved a reload issue with gulp and browserSync

The gulp build for my small express app– now with react integrated for some components on the frontend– was running into a strange issue when making edits.

I had set up the gulp process such that it reloaded at the end of a file watch, once that watch was triggered:

// Debounce function to limit reload frequency
const debounce = (fn, delay) => {
  let timer;
  return () => {
    clearTimeout(timer);
    timer = setTimeout(fn, delay);
  };
};

const debouncedReload = debounce(() => browserSync.reload(), 300);

function reload() {
  debouncedReload();
}
watch("sass/**/**.scss", gulp.series(generateCSS, reload));

As the code indicates, the gulp script utilizes browserSync for the reloading. I have browserSync configured to serve the site via proxy:

function serve(done) {
  browserSync.init({
     injectChanges: false,
    files: ["./**/*"],  
    proxy: "http://localhost:3000/",
    port: 5001,
  });
  done();
}

This sync watches all files. When a change is made, it reloads the active port.

At the same time, my gulp watch was trying to force a reload as well. Something about the two reloads running simultaneously was allowing a successful reload on first edit, but never again after that. Removing the reload function from the watch resolved this:

watch("sass/**/**.scss", gulp.series(generateCSS));

I can also removed the series wrapper, but I will save that for the next commit 🙂


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *