How to deal with browser cache while using browserSync?

why don't you use gulp-cache

var cache = require('gulp-cache');   

gulp.task('clearCache', function() {

  // Still pass the files to clear cache for
  gulp.src('./lib/*.js')
  .pipe(cache.clear());

  // Or, just call this for everything
  cache.clearAll();

});

and then add this task to your watcher


In chrome devtools (CTRL MAJ I), in Network tab, you have a Disable cache checkbox. It should work.


Found a solution through using {stream: true} parameter of browserSync.reload function, but to make it work, some changes required. So how it was:

gulp.watch('/public/js/**/*.js').on('change', browserSync.reload);

and how it looks now:

gulp.watch('/public/js/**/*.js').on('change', function(e) {
    return gulp.src(e.path)
        .pipe(browserSync.reload({stream: true}));
});

This solved my problem:

1- Install gulp-cache npm package

npm i gulp-cache

2-Require this package in your gulpfile.js by adding the following line:

const cache = require('gulp-cache');

3- Now you want to create a gulp task that clear the cache using gulp-cache:

function clearCache(done) {
  return cache.clearAll(done);
}

4- Finally update your watch task, I'll share mine as a reference:

function watch() {
  browserSync.init({
    server: './dist',
  });
  gulp.watch('sass/**/*.scss', gulp.parallel(styles));
  gulp.watch('sass/**/*.scss').on('change', clearCache, browserSync.reload);
  gulp.watch('index.html', gulp.parallel(copyHtml));
  gulp.watch('*.html').on('change', browserSync.reload);
  gulp.watch('js/**/*.js', gulp.series(lint, scripts));
  gulp.watch('js/**/*.js').on('change', clearCache, browserSync.reload);
  gulp.watch('img/**/*.jpg', gulp.series(copyImages));
  gulp.watch('img/**/*').on('change', clearCache, browserSync.reload);
}

If you look closely you'll notice I change each of my gulp.watch by adding clear cache to the list of function to run after change:

gulp.watch('sass/**/*.scss', gulp.parallel(styles));
gulp.watch('sass/**/*.scss').on('change', clearCache, browserSync.reload);

Please let me know if this works for you!