基于html属性为gullow构建过程添加条件

Add condition to gulp building process based on html attribute

本文关键字:过程 添加 条件 构建 gullow html 属性 基于      更新时间:2023-09-26

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

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

您可以使用gulp-replacement来更改每个标签。。。

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

这将为每个图像添加属性。如果你想要更多的控制,你可以使用gullow-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'));
});