【问题标题】:gulp-replace if content of files match regex如果文件内容与正则表达式匹配,则 gulp-replace
【发布时间】:2016-07-13 00:18:54
【问题描述】:

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

最有效的方法是什么?

【问题讨论】:

  • 这是.pipe($.replace(template_data, '')) 不是.pipe($.replace, template_data, '')
  • 有趣的是,我使用的框架在其 gulpfile 中有两种变体。

标签: gulp pipeline gulp-replace gulp-if


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2010-11-18
    相关资源
    最近更新 更多