如果内容包含字符串,则从 Gulp 流中排除文件

Exclude files from Gulp stream if contents contain a string

我有一个 gulp 任务,看起来像这样:

    return src(['storage/framework/views/*.php'])
        .pipe(htmlmin({
            collapseWhitespace: true,
        }))
        .pipe(dest('storage/framework/views'));

它从 Laravel 中获取已编译的视图,并通过 htmlmin 将它们通过管道传输。

这适用于 HTML 视图,但会破坏 Markdown 视图的内容。

不幸的是,我无法在 src([...]) 中添加排除项,因为文件名都是哈希值。我需要能够检查文件的内容并在文件包含 mail::message.

时排除该文件

试图自己解决这个问题,有 gulp-contains,但如果文件包含给定的字符串,那似乎只能抛出错误。我想不出一种方法来使用它的回调来排除文件。

还有 gulp-ignore,但似乎无法从流中排除单个文件。

假设有三个模板文件,其中y.php是一个Markdown模板。理想的解决方案是这样的:

    return src(['storage/framework/views/*.php']) // [x.php, y.php, z.php]
        .pipe(exclude_files_containing('mail::message')) // [x.php, z.php]
        .pipe(htmlmin({
            collapseWhitespace: true,
        }))
        .pipe(dest('storage/framework/views'));

使用gulp-filter

const filter = require('gulp-filter');

gulp.task("TaskExample", function () {

  // return true if want the file in the stream
  // return file to exclude the file

  const excludeMessageFilter = filter(function (file) {

    let contents = file.contents.toString();
    return !contents.match('mail::message');
  });

  return gulp.src('storage/framework/views/*.php')

    .pipe(excludeMessageFilter)

    // .pipe(htmlmin(...
    // .pipe(gulp.dest('''''''));
});