I have a problem with Gulp and BrowserSync, is really a small issue but is bugging me.
Every time I change the scss file and I ran sass() to combile it the browser reloads and scrolls back to the top.
Is there a way to prevent the browser to do that every time I change a scss file?
By the way this is happening only on the sass task, the js and php tasks do not cause the browser to scroll to the top.
I tried Chrome and Firefox and I get the same behavior.
Here is my gulpfile.js
gulp.task('serve', ['sass'], function() {
browserSync.init({
proxy: "mysite.dev"
});
gulp.watch("styles/scss/*.scss", ['sass']);
gulp.watch("*scripts/*.js", ['js']);
gulp.watch("*.php", ['php']);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return gulp.src("styles/scss/*.scss")
.pipe(sass())
.pipe(gulp.dest("styles/css"))
.pipe(browserSync.stream());
});
gulp.task('js', function() {
return gulp.src('scripts/*.js')
.pipe(browserSync.stream());
});
gulp.task('php', function() {
return gulp.src('*.php')
.pipe(browserSync.stream());
});
gulp.task('default', ['serve']);
Is there a way to stop that?
Update - Two days later and I can't reproduce the issue anymore. Not sure if below code actually solved it.
Solution: Appending .on('change', browserSync.reload)
to your Gulp Sass watch line should stop your browser scroll from resetting when saving a SCSS file.
(Note - Gulp v4)
gulp.watch('scss/**/*.scss', sassCompile).on('change', browserSync.reload) // Gulp v4 version
gulpfile.js example:
var gulp = require('gulp');
const { series } = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
function serve(){
browserSync.init({
server: {
baseDir: "./"
},
});
gulp.watch('scss/**/*.scss', sassCompile).on('change', browserSync.reload);
gulp.watch('./css/*.css').on('change', browserSync.reload);
gulp.watch("./*.html").on('change', browserSync.reload);
}
exports.serve = serve;
function sassCompile(cb) {
return gulp
.src('./scss/*.scss')
.pipe(sass()) // Converts Sass to CSS with gulp-sass
.pipe(gulp.dest('css'))
.pipe(browserSync.stream());
cb();
}
exports.sass = sassCompile;
exports.default = series(serve);
To run: Enter in command line
gulp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With