gulp-replace如果文件内容与正则表达式匹配

时间:2016-07-13 00:18:55

标签: gulp pipeline gulp-replace gulp-if

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

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

最有效的方法是什么?

1 个答案:

答案 0 :(得分:0)

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