Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gulp 4 & BrowserSync: Style Injection?

I'm attempting to use browser-sync with Gulp 4, but bs is not preserving state, and instead does a full refresh. This is not very useful. It seems bs no longer supports true injection. I filed an issue on GH if you want to contribute.

Here is the pertinent code:

// styles:dev task    
gulp.task('styles:dev', function() {
    return gulp.src(config.src)
        .pipe(sourcemaps.init())
        .pipe(postcss(config.postcss.dev))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(config.dest.dev))
        .pipe(browserSync.stream());
});

// browserSync task    
gulp.task('browserSync', function(cb) {
    browserSync.init(config, cb);
});

// Watch task:
gulp.task('watch:styles', function() {
    return gulp.watch(config.paths.css,
        gulp.series('styles:dev'));
});

gulp.task('watch', gulp.parallel('watch:styles'));

// default task    
gulp.task('default',
    gulp.series('clean:dev',
        gulp.parallel('copy:dev', 'styles:dev'), 'browserSync', 'watch')
);

Thanks in advance.

like image 267
JamesJosephFinn Avatar asked Jan 03 '16 23:01

JamesJosephFinn


People also ask

What is gulp used for?

Gulp is a tool that helps you out with several tasks when it comes to web development. It's often used to do front end tasks like: Spinning up a web server. Reloading the browser automatically whenever a file is saved.

What version of Node works with gulp 4?

Gulp 3.9. 1 will work with Node 8 (latest noded 8 is 8.17.


1 Answers

Fixed. Here's where I went wrong:

The browser-sync constructor takes an options object, which can include a files array. Most of the tutorials I've read, including the gulpfile for Google's very own Web Starter Kit, do not include this. As it turns out, this is required for style injection to preserve state.

Furthermore, do not pass .stream() or .reload() as the final pipe in your styles task. It is not needed, and will short circuit style injection, forcing a full refresh.

Finally, the browserSync process must not be terminated, and watch and browserSync tasks must execute in parallel in order for live style injection to take place.

Hope this helps anybody facing this issue.

I also closed the corresponding github issue, and posted my gulpfile

like image 60
JamesJosephFinn Avatar answered Sep 18 '22 06:09

JamesJosephFinn