Search code examples
gulpgoogle-web-starter-kit

Running 'gulp-preprocess' as part of 'gulp serve' task


I am basing my project off Google Web Starter Kit and am looking to integrate gulp-preprocess into the gulp pipeline.

I have managed to get it to work for the gulp serve:dist task, the relevant code is:

 gulp.task('htmlIncludes', function() {
      gulp.src('app/*.html')
        .pipe(preprocess({context: { NODE_ENV: 'production', DEBUG: true}})) 
        .pipe(gulp.dest('./dist/'))
    }); 

    gulp.task('default', ['clean'], function (cb) {
      runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy', 'htmlIncludes'], cb);
    });

However, I am having trouble getting it to work for the gulp:serve task which includes browser sync:

gulp.task('serve', ['styles'], function () {
  browserSync({
    notify: false,
    server: ['.tmp', 'app']
  });

I would like to add the htmlIncludes task, so that it is re-run when files are updated while running gulp:serve. However, simply adding it to the list which currently includes 'styles' does not have the desired effect. Any idea what I need to change?


Solution

  • You are totally right, you have to add it to the dependencies of this task to be run at least once. However, this is just half of the story. You have to run your task each time your HTML files have changed, so add it to the respective watch process:

    gulp.task('serve', ['styles', 'htmlIncludes'], function () {
        browserSync({
            notify: false,
            logPrefix: 'WSK',
            server: ['.tmp', 'app']
        });
    
        // here's the change
        gulp.watch(['.tmp/**/*.html', 'app/**/*.html'], ['htmlIncludes', reload]);
        gulp.watch(['app/styles/**/**/**/**/*.{scss,css}'], ['styles', reload]);
        gulp.watch(['app/scripts/**/*.js'], ['jshint']);
        gulp.watch(['app/images/**/*'], reload);
    });
    

    You also see that this browserSync call just serves .tmp and app folders, while your output is stored in dist. So you have to change your htmlIncludes task, too:

    gulp.task('htmlIncludes', function() {
         return gulp.src('app/*.html')
             .pipe(preprocess({context: { NODE_ENV: 'production', DEBUG: true}})) 
             .pipe(gulp.dest('./.tmp/'))
             .pipe(gulp.dest('./dist/'))
    }); 
    

    If you need separate configurations for each output, we have to tackle it again. But for now it should work as planned.

    It also might be possible that you have to run the 'html' task in sequence first, but I'm not that fit in the WSK Gulpfile to answer you that ;-)