browser-sync used with gulp does not refresh the page in the browser even for a simple setup.
Versions: gulp: 4.0.2, browser-sync: 2.26.7, Chrome: 81.0.4044.138
Folder structure:
|- src/
|- index.html
|- dist
gulpfile.js:
const { task, src, dest, series, watch } = require('gulp');
const browserSync = require('browser-sync').create();
task('html', () => {
return src('src/*.html').pipe(dest('dist'));
});
task('browserSync', () => {
browserSync.init({
server: {
baseDir: 'dist'
}
});
});
task(
'watch',
series(
task('html'),
(done) => {
watch('src/*.html', task('html'));
watch('dest/*.html').on('change', browserSync.reload);
done();
},
task('browserSync')
)
);
When I run gulp watch, src/index.html is successfully copied to dest/index.html, and browser-sync is started (Chrome opens the page and shows me "Browsersync connected").
When I make any changes in src/index.html, it is copied to dest/index.html but browser-sync doesn't refresh the page.
I tried replacing browserSync.reload with () => console.log('reloaded') inside watch('dist/*.html').on('change', ...) call, and the log message is shown successfully every time I change src/index.html file (which means that the watcher works properly and browserSync.reload is called). Also tried restarting Chrome.
Any help or advice would be much appreciated.
Update: it starts working if I put watch('dist/*.html', browserSync.reload); inside the browserSync task (which is strange):
task('browserSync', () => {
browserSync.init({
server: {
baseDir: 'dist'
}
});
watch('dist/*.html', browserSync.reload);
});
Another option that helps is adding files property to make browser-sync create its own file watcher:
task('browserSync', () => {
browserSync.init({
server: {
baseDir: 'dist'
},
files: [ 'dist/*.html' ]
});
});