【问题标题】:Add condition to gulp building process based on html attribute基于 html 属性为 gulp 构建过程添加条件
【发布时间】:2016-12-14 00:24:45
【问题描述】:

是否可以添加一个条件,使我项目中所有 html 文件中的每个 img 标记都应具有另一个属性,例如 my-custom-directive

我有一个 angular 指令,它修改了我的 webapp 中相对 img src URL 的基本 URL,我想防止我的团队成员在他们编写的 html 模板中丢失这个属性。

【问题讨论】:

    标签: javascript html angularjs gulp bower


    【解决方案1】:

    您可以使用gulp-replace 更改每个标签...

    var replace = require('gulp-replace');
    
    gulp.task('pages', function(){
      gulp.src(['*.html'])
        .pipe(replace(/<img/g, '<img my-custom-directive'))
        .pipe(gulp.dest('build'));
    });
    

    这会将属性添加到每个图像。如果你想要更多的控制,你可以使用gulp-tap 来获取整个文件的内容并处理它。

    var tap = require('gulp-tap');
    
    gulp.task('pages', function(){
      gulp.src(['*.html'])
      .pipe(tap(function(file) {
    
      // get current contents
      let contents = file.contents.toString();
    
      // do your conditional processing
      // eg deal with each tag in a loop & only change those without the attribute
      contents = contents.replace(/<img/g, '<img my-custom-directive'); 
    
      // set new contents to flow through the gulp stream
      file.contents = new Buffer(contents);
    }))
    .pipe(gulp.dest('build'));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 2018-01-31
      • 1970-01-01
      • 2022-11-03
      • 2019-06-29
      • 2014-02-03
      • 1970-01-01
      相关资源
      最近更新 更多