GULP : how to watch for new images while using browserSync?

2k views Asked by At

I can't figure out how to watch for new files with gulp-watch and apply gulp-image while using my browserSync... When I add a new image in my image folder (./fixtures/*), nothing happen. I would do it manually in the command line but I would have to close my browserSync (not really a viable solution). So... here's what my gulpfile.js looks like :

var input = "./scss/*.scss";
var output = "./"
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var sassdoc = require('sassdoc');
var image = require('gulp-image');

// scss + sourceMaps

gulp.task('styles', function() {
  gulp.src(input)
    .pipe(sourcemaps.init())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(sourcemaps.write('./maps'))
    .pipe(gulp.dest(output))
    .pipe(browserSync.reload({stream: true}));
});

// scss + browserSync

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

    browserSync.init({
        server: {
          baseDir: output
        }
    });

    gulp.watch(input, ['styles']);
    gulp.watch("./**/*.html").on('change', browserSync.reload);
});

// sassDoc activation

gulp.task('sassdoc', function () {
  return gulp.src(input)
    .pipe(sassdoc());
});

// image minification

gulp.task('image', function() {
  gulp.watch('./fixtures/*.{png,jpg,jpeg,gif,svg}', function() {
    gulp.src('./fixtures/*.{png,jpg,jpeg,gif,svg}')
      .pipe(image())
      .pipe(gulp.dest('./img'));
  });
});

gulp.task('default', ['styles', 'serve', 'image']);
1

There are 1 answers

1
Mark On

Modify the seve task like so:

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

  browserSync.init({
    server: {
      baseDir: output
    }
  });

  gulp.watch(input, ['styles']);
  gulp.watch("./**/*.html").on('change', browserSync.reload);
  // gulp.watch('./fixtures/*.{png,jpg,jpeg,gif,svg}', ['image']);
  gulp.watch('fixtures/*.{png,jpg,jpeg,gif,svg}', {cwd: './'} ['image']);
});

and then simplify the 'image' task to :

gulp.task('image', function() {
 return gulp.src('./fixtures/*.{png,jpg,jpeg,gif,svg}')
  .pipe(image())
  .pipe(gulp.dest('./img'));
});

You probably want to add gulp-cached or gulp-remember to your image pipeline so you are not minifying all images each time one is changed or added.

Also, remember to add return statements to your tasks like I did with image; the 'styles' task needs a return statement.

EDIT : See the edit above, it looks like gulp.watch doesn't like a glob starting with "./" from other questions such as gulp.watch not watching added or deleted files. I haven't tested this for myself though.