首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >gulp如果文件内容与正则表达式匹配,则替换

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

Stack Overflow用户
提问于 2016-07-13 08:18:55
回答 1查看 986关注 0票数 0

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

代码语言:javascript
复制
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'));
}

做这件事最有效的方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-14 03:29:14

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

代码语言:javascript
复制
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'));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38340780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档