-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
83 lines (67 loc) · 2.2 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
var fs = require('fs'),
path = require('path'),
postcss = require('postcss');
function getUrl(value) {
var reg = /url\((\s*)(['"]?)(.+?)\2(\s*)\)/g,
match = reg.exec(value),
url = match[3];
return url;
}
function replaceFiles(string, opts) {
file = getUrl(string);
ext = path.extname(file).replace('.', '');
if(ext === 'svg') ext = ext + '+xml';
fileContents = fs.readFileSync(path.join(opts.root, file));
output = 'data:image/' + ext + ';base64,' + fileContents.toString('base64');
return string.replace(file, output);
}
function replaceInline(string, opts) {
output = new Buffer(string).toString('base64');
if(opts.prepend) output = opts.prepend + output;
return output;
}
module.exports = postcss.plugin('postcss-base64', function (opts) {
return function (css, result) {
opts = opts || {};
var exts,
ext,
search,
file,
fileContents,
output;
if(!opts.root) {
opts.root = process.cwd();
}
if(opts.excludeAtFontFace === undefined) {
opts.excludeAtFontFace = true;
}
if(opts.extensions) {
exts = '\\' + opts.extensions.join('|\\');
search = new RegExp('url\\(.*(' + exts + ').*\\)', 'i');
css.each(function (node) {
if(
opts.excludeAtFontFace &&
node.type === 'atrule' &&
node.name === 'font-face'
) {
// Don't do @font-face rules
return;
};
if(node.replaceValues) {
node.replaceValues(search, function (string) {
return replaceFiles(string, opts);
});
}
});
}
if(opts.pattern) {
if(!opts.pattern instanceof RegExp) {
throw new Error('Given search pattern is not a (valid) regular expression.');
}
search = opts.pattern;
css.replaceValues(search, function (string) {
return replaceInline(string, opts);
});
}
};
});