运行 'gulp-preprocess' 作为 'gulp serve' 任务的一部分

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

我的项目基于 Google Web Starter Kit,并希望将 gulp-preprocess 集成到 gulp 管道中。

我已经设法让它为gulp serve:dist任务工作,相关代码是:

 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);
    });

但是,我无法让它为包含浏览器同步的 gulp:serve 任务工作:

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

我想添加htmlIncludes任务,以便在运行宁gulp:serve时更新文件时重新运行。但是,简单地将其添加到当前包含 'styles' 的列表中并没有达到预期的效果。知道我需要更改什么吗?

你完全正确,你必须至少将它添加到此任务的依赖项中 运行 一次。然而,这只是故事的一半。每次 HTML 文件更改时,您都必须 运行 您的任务,因此将其添加到相应的 watch 进程:

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);
});

您还看到此 browserSync 调用仅服务于 .tmpapp 文件夹,而您的输出存储在 dist 中。所以你也必须改变你的 htmlIncludes 任务:

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/'))
}); 

如果您需要为每个输出单独配置,我们必须再次解决它。但目前它应该按计划工作。

您也可能必须先按顺序 运行 'html' 任务,但我不适合在 WSK Gulpfile 中回答您 ;-)