Search code examples
gulpgulp-watch

Rebuild all files if template changes


I'm using gulp to convert markdown files to HTML, and using the gulp-watch plugin (not the gulp.watch API function) to rebuild files if they change. Works great!

gulp.task('markdown', function () {
  gulp.src('src/**/*.md')
      .pipe(watch('src/**/*.md'))
      .pipe(markdown())
      .pipe(template('templates/md.tpl'))
      .pipe(gulp.dest('dist'));
});

The problem is that the pipeline src is the markdown files, but within the pipeline I also reference a template file. If that template changes, all the markdown files need to be rebuilt. Is there a way to express that dependency in gulp/gulp-watch?

I tried using gulp.watch (the API function) to watch the template and run the 'markdown' task if it changes ...

gulp.watch('templates/md.tpl', ['markdown']);

... but that didn't work. Nothing happens. I assume having gulp-watch in the pipeline prevents it from doing anything.

I guess I could create a two tasks, one with gulp-watch and one without, and use the one without to force a full rebuild. I'd rather not, because then it becomes an ongoing problem to keep the two in sync.

Is there a better way?


Solution

  • I guess I could create a two tasks, one with gulp-watch and one without, and use the one without to force a full rebuild. I'd rather not, because then it becomes an ongoing problem to keep the two in sync.

    Remember, gulp is just JavaScript.

    Simply write a function that constructs the stream with or without the watch() step depending on a parameter that you pass. The gulp-if plugin let's you write something like this in a very concise way (although it's not necessary and could be done without it).

    Here's how I would do it:

    var gulpIf = require('gulp-if');
    
    function processMarkdown(opts) {
      gulp.src('src/**/*.md')
        .pipe(gulpIf(opts.watch, watch('src/**/*.md')))
        .pipe(markdown())
        .pipe(template('templates/md.tpl'))
        .pipe(gulp.dest('dist'));
    }
    
    gulp.task('markdown', function() {
      processMarkdown({watch: true});
      watch('templates/md.tpl', function() {
        processMarkdown({watch: false});
      });
    });