-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (65 loc) · 2.11 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const url = require('url');
const through2 = require('through2');
const PluginError = require('plugin-error');
function cssAddRev(content, time) {
const cssRegex = /<link.*href\=\"([^\"]*)\"/gi;
const matches = content.matchAll(cssRegex);
for (const match of matches) {
const urlObj = url.parse(match[1]);
const qsObj = new URLSearchParams(urlObj.search);
qsObj.set('v', time);
let revUrl = '';
let revStr = '';
if (urlObj.search) {
revUrl = match[1].replace(urlObj.search, '?' + qsObj.toString());
revStr = match[0].replace(match[1], revUrl);
} else {
revUrl = match[1] + '?' + qsObj.toString();
revStr = match[0].replace(match[1], revUrl);
}
content = content.replace(match[0], revStr);
}
return content;
}
function jsAddRev(content, time) {
const cssRegex = /<script.*src\=\"([^\"]*)\"/gi;
const matches = content.matchAll(cssRegex);
for (const match of matches) {
const urlObj = url.parse(match[1]);
const qsObj = new URLSearchParams(urlObj.search);
qsObj.set('v', time);
let revUrl = '';
let revStr = '';
if (urlObj.search) {
revUrl = match[1].replace(urlObj.search, '?' + qsObj.toString());
revStr = match[0].replace(match[1], revUrl);
} else {
revUrl = match[1] + '?' + qsObj.toString();
revStr = match[0].replace(match[1], revUrl);
}
content = content.replace(match[0], revStr);
}
return content;
}
function plugin() {
return through2.obj(function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new PluginError('gulp-rev-html', 'Streaming not supported'));
return;
}
const fileInfo = {
content: file.contents.toString()
};
const time = parseInt(new Date().getTime() / 1000);
fileInfo.content = cssAddRev(fileInfo.content, time);
fileInfo.content = jsAddRev(fileInfo.content, time);
file.contents = Buffer.from(fileInfo.content);
this.push(file);
cb();
});
};
module.exports = plugin;