-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (69 loc) · 1.98 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const gutil = require('gulp-util');
const PluginError = gutil.PluginError;
const through = require('through2');
const pluginName = 'gulp-webp-html2';
module.exports = function () {
var extensions = ['.jpg', '.png', '.jpeg'];
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new PluginError(pluginName, 'Streaming not supported'));
return;
}
try {
var SplitPicture = '<picture>';
var RePicture = /([\s\S]*?<\/picture>)([\s\S]*)/;
var SplitImg = '<img ';
var ReImg = /<img([^>]*)src=[\"\'](\S+)[\"\']([^>]*)>/;
const data = file.contents.toString()
.split(SplitPicture)
.map(function (line) {
var picture = '';
if (RePicture.test(line)) {
var lineA = line.match(RePicture);
picture = lineA[1];
line = lineA[2];
}
if (~ line.indexOf(SplitImg)) {
var lineNew = line
.split(SplitImg)
.map(function (subLine) {
var lineImg = (SplitImg + subLine).toString();
if (ReImg.test(lineImg)) {
subLine = lineImg;
var regexpArray = lineImg.match(ReImg);
var imgTag = regexpArray[0];
var newUrl = regexpArray[2];
if (! ~ newUrl.indexOf('.webp')
&& ! /\sdata-no-webp[\=\s]/g.test(imgTag)) {
for (var k in extensions) {
if (~ newUrl.indexOf(extensions[k])) {
newUrl = newUrl.replace(extensions[k], '.webp');
var newHTML = '<picture><source srcset="'
+ newUrl + '" type="image/webp">'
+ imgTag + '</picture>';
subLine = lineImg.replace(imgTag, newHTML);
break;
}
}
}
}
return subLine;
})
.join('');
line = lineNew;
}
return picture + line;
})
.join(SplitPicture);
file.contents = new Buffer(data);
this.push(file);
} catch (err) {
this.emit('error', new PluginError(pluginName, err));
}
cb();
});
};