0

我有一个 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'));
}

解决此问题的最有效方法是什么?

4

1 回答 1

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'));
}
于 2016-07-13T19:29:14.087 回答