根据 html 属性向 gulp 构建过程添加条件
Add condition to gulp building process based on html attribute
是否可以添加一个条件,使我的项目中所有 html 文件中的每个 img
标记都应具有另一个属性,例如 my-custom-directive
?
我有一个 angular 指令,它修改我的 webapp 中相对 img src URL 的基础 URL,我想防止我的团队成员在html 他们写的模板。
您可以使用 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'));
});
是否可以添加一个条件,使我的项目中所有 html 文件中的每个 img
标记都应具有另一个属性,例如 my-custom-directive
?
我有一个 angular 指令,它修改我的 webapp 中相对 img src URL 的基础 URL,我想防止我的团队成员在html 他们写的模板。
您可以使用 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'));
});