-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
84 lines (70 loc) · 2.38 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
"use strict";
var path = require('path');
var crypto = require('crypto');
var fs = require('fs');
var gutil = require('gulp-util');
var through = require('through2');
var PLUGIN_NAME = 'gulp-css-urlversion';
function md5ify(data) {
var hash = crypto.createHash("md5");
hash.update(data);
return hash.digest("hex");
}
module.exports = function(options) {
options = options || {};
var baseDir = options.baseDir || process.cwd();
var ignoreFonts = options.ignoreFonts || false;
var ignoreSvg = options.ignoreSvg || false;
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
return;
}
var incoming = file.contents.toString();
var outgoing = incoming.replace(/url(\([\s]*[^;,}]*[\s]*\))/g, function (str, dirtyUrl) {
var url = dirtyUrl.replace(/^\(/g,'').replace(/\)$/g,'').replace(/'|"/g, '').trim();
var replaceWithStr = null;
var isFont = url.indexOf(".eot") > -1
|| url.indexOf(".woff") > -1
|| url.indexOf(".ttf") > -1
|| url.indexOf(".otf") > -1;
var isSvg = url.indexOf(".svg") > -1;
if ((isFont && ignoreFonts)
|| (isSvg && ignoreSvg)
|| url.indexOf("base64,") > -1
|| url.indexOf("http://") > -1
|| url.indexOf("https://") > -1
) {
replaceWithStr = str; // ignoring fonts, base64 and external links
} else {
var filePath = file.path || __filename;
var imagePath = null;
if (url.indexOf('/') === 0) { // root-relative url
imagePath = path.join(baseDir, url);
} else { // this path should be threated as relative
imagePath = path.resolve(path.dirname(filePath), url);
}
try {
var idata = fs.readFileSync(imagePath);
replaceWithStr = 'url(' + url + "?v=" + md5ify(idata) + ')';
} catch (err) {
replaceWithStr = str;
console.dir(file);
this.emit('error', new gutil.PluginError(PLUGIN_NAME, err, {fileName: file.path}));
}
}
return replaceWithStr;
}.bind(this));
try {
file.contents = new Buffer(outgoing);
this.push(file);
} catch (err) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, err, {fileName: file.path}));
}
cb();
});
};