Search code examples
javascriptgulpbrowser-sync

browser sync seems not work


first time I'm using browser sync with gulp, this is my project structure:

-root
    -assets
        -img
    -src
        -css
        -js
        -scss
        index.html
    gulpfile.js
    package.json

and this is the gulpfile.js:

const gulp        = require('gulp');
const browserSync = require('browser-sync').create();
const sass        = require('gulp-sass');

gulp.task('sass', function() {
    return gulp.src("./src/scss/*.scss")
        .pipe(sass())
        .pipe(gulp.dest("./src/css"))
        .pipe(browserSync.stream());
});

// Static Server + watching scss/html files
gulp.task('serve', gulp.series('sass'), () => {

    browserSync.init({
        server: "./src"
    });

    gulp.watch("./src/scss/*.scss", ['sass']);
    gulp.watch("./src/*.html").on('change', browserSync.reload({stream:true}));
});

// Compile sass into CSS & auto-inject into browsers


gulp.task('default', gulp.series('serve'));

I take the code by the browser sync docs here and modified a bit, but when I type 'gulp' on the console, I get this:

[22:24:59] Starting 'default'...
[22:24:59] Starting 'serve'...
[22:24:59] Starting 'sass'...
[22:24:59] Finished 'sass' after 40 ms
[22:24:59] Finished 'serve' after 43 ms
[22:24:59] Finished 'default' after

Probably I missed something, shouldn't browser sync run indefinitely? thanks


Solution

  • ok now seems I solved:

    const gulp        = require('gulp');
    const browserSync = require('browser-sync').create();
    const sass        = require('gulp-sass');
    
    gulp.task('sass', function() {
        return gulp.src("./src/scss/*.scss")
            .pipe(sass().on('error', sass.logError))
            .pipe(gulp.dest("./src/css"))
            .pipe(browserSync.stream());
    });
    
    // Static Server + watching scss/html files
    gulp.task('serve', function() {
    
        browserSync.init({
            injectChanges: true,
            server: "./src"
        });
    
        gulp.watch("./src/scss/*.scss", gulp.series('sass'));
        gulp.watch("./src/*.html").on('change', browserSync.reload);
    });
    
    // Compile sass into CSS & auto-inject into browsers
    
    
    gulp.task('default', gulp.series('serve','sass'));