gulp-如果文件内容匹配正则表达式则替换

gulp-replace if content of files match regex

我有一个包含 HTML 个文件的文件夹,其中包含顶部带有元数据的评论。如果元数据与一个正则表达式匹配,我想 运行 一个 gulp-replace 操作,如果不匹配,我想另一个 gulp-replace 操作,然后继续任务管道的其余部分。如果尝试使用 gulp-if 进行各种迭代,但它总是会导致 "TypeError: undefined is not a function" 错误

import gulp    from 'gulp';
import plugins from 'gulp-load-plugins';

const $ = plugins();

function preprocess() {
  var template_data = new RegExp('<!-- template_language:(\w+)? -->\n', 'i');
  var handlebars = new RegExp('<!-- template_language:handlebars -->', 'i');
  var primaryColor = new RegExp('#dc002d', 'gi');
  var mailchimpColorTag = '*|PRIMARY_COLOR|*';
  var handlebarsColorTag = '{{PRIMARY_COLOR}}';

  var replaceCondition = function (file) {
    return file.contents.toString().match(handlebars);
  }

  return gulp.src('dist/**/*.html')
    .pipe($.if(
      replaceCondition,
      $.replace(primaryColor, handlebarsColorTag),
      $.replace(primaryColor, mailchimpColorTag)
    ))
    .pipe($.replace, template_data, '')
    .pipe(gulp.dest('dist'));
}

最有效的方法是什么?

gulp-filter 就是答案。 gulp-if 可用于决定是否应将特定操作应用于整个流,而 gulp-filter 可用于决定应将操作应用于流中的哪些文件。

import gulp    from 'gulp';
import plugins from 'gulp-load-plugins';

const $ = plugins();

function preprocess() {
  var template_language = new RegExp('<!-- template_language:(\w+)? -->\n', 'i');
  var handlebars = 'handlebars';
  var primaryColor = new RegExp('#dc002d', 'gi');
  var handlebarsColorTag = '{{PRIMARY_COLOR}}';
  var handlebarsCondition = function (file) {
    var match = file.contents.toString().match(template_language);
    return (match && match[1] == handlebars);
  }
  var handlebarsFilter = $.filter(handlebarsCondition, {restore: true});
  var mailchimpColorTag = '*|PRIMARY_COLOR|*';
  var mailchimpCondition = function (file) {
    return !handlebarsCondition(file);
  }
  var mailchimpFilter = $.filter(mailchimpCondition, {restore: true});

  return gulp.src('dist/**/*.html')
    .pipe(handlebarsFilter)
    .pipe($.replace(primaryColor, handlebarsColorTag))
    .pipe($.debug({title: 'Applying ' + handlebarsColorTag}))
    .pipe(handlebarsFilter.restore)
    .pipe(mailchimpFilter)
    .pipe($.replace(primaryColor, mailchimpColorTag))
    .pipe($.debug({title: 'Applying ' + mailchimpColorTag}))
    .pipe(mailchimpFilter.restore)
    .pipe($.replace(template_language, ''))
    .pipe(gulp.dest('dist'));
}