How to make Gulp wait until dest file is finished?

Jaakko Karhu picture Jaakko Karhu · Apr 20, 2016 · Viewed 8.1k times · Source

I want to run gulp-sass and after that check, what is the size of the generated css file.

If I have the following in my gulpfile:

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

  gulp.src('src/scss/style.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sass({outputStyle: 'expanded'}))
    .pipe(gulp.dest(buildPath+'css'))
    .pipe(connect.reload());
});

gulp.task('css.size', ['sass'], function() {
  gulp.src(buildPath+'css/style.css')
      .pipe(filesize())
})

gulp.task('default', ['clear','copy', 'sass', 'connect'], function() {

  gulp.watch(['./src/**/*.js', './src/*/**.html'], ['copy', 'reload']);
  gulp.watch('./src/**/*.scss', ['sass']);
  gulp.watch(buildPath+'css/style.css', ['css.size']);
});

I end up in the never ending limbo of building css file, apparently because the css.size task has to wait for the sass task to finish. Correct me if I am wrong. For me it does not make sense, but I have not found any other explanation, especially because if I comment the style.css watch task, the sass task is ran only once, as expected.

Now, if I modify the gulpfile like this:

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

  gulp.src('src/scss/style.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sass({outputStyle: 'expanded'}))
    .pipe(gulp.dest(buildPath+'css'))
    .pipe(connect.reload());
});

gulp.task('css.size', ['sass'], function() {
  gulp.src(buildPath+'css/style.css')
      .pipe(filesize())
})

gulp.task('default', ['clear','copy', 'sass', 'connect'], function() {

  gulp.watch(['./src/**/*.js', './src/*/**.html'], ['copy', 'reload']);
  gulp.watch('./src/**/*.scss', ['sass', 'css.size']);
});

or like this

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

  gulp.src('src/scss/style.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sass({outputStyle: 'expanded'}))
    .pipe(gulp.dest(buildPath+'css'))
    .pipe(connect.reload());
  gulp.src(buildPath+'css/style.css')
      .pipe(filesize())
});

gulp.task('default', ['clear','copy', 'sass', 'connect'], function() {

  gulp.watch(['./src/**/*.js', './src/*/**.html'], ['copy', 'reload']);
  gulp.watch('./src/**/*.scss', ['sass']);
});

I get the wrong results. The file is apparently not compiled yet and I get the file size of the old file.

How should I arrange my tasks so I could get the file size of freshly built css file?

Answer

sebbab picture sebbab · Apr 20, 2016

Make your sass task return the stream. Like this:

gulp.task('sass', function () {
  return gulp.src('src/scss/style.scss')
    .pipe(sass.sync().on('error', sass.logError))
    .pipe(sass({outputStyle: 'expanded'}))
    .pipe(gulp.dest(buildPath+'css'))
    .pipe(connect.reload());
});

Note the return before the gulp.src. That way, the css.size task will know when the sass task finishes, and start after it.