-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
68 lines (62 loc) · 1.71 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
var fs = require('fs');
var path = require('path');
var sizeOf = require('image-size');
var mustache = require('mustache');
var through = require('through');
var gutil = require('gulp-util');
var mime = require('mime');
var SVGO = require('svgo');
var svgo = new SVGO();
function strictEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
module.exports = function(opts) {
var tpl = fs.readFileSync(opts.styleTemplate).toString();
var buffer = [];
var svgs = [];
var prefix = opts.prefix !== undefined ? opts.prefix : 'url(';
var sufix = opts.sufix !== undefined ? opts.sufix : ')';
var bufferContents = function(file) {
var type = mime.lookup(file.path);
var dim = sizeOf(file.path);
if(type !== 'image/svg+xml') {
// console.log(imgData, dim);
dim.data = [
prefix + 'data:',
mime.lookup(dim.type),
';base64,',
file.contents.toString('base64'),
sufix
].join('');
dim.name = path.basename(file.path, '.' + dim.type);
buffer.push(dim);
} else if(type === 'image/svg+xml') {
svgo.optimize(file.contents.toString(), function(res) {
dim = {
width: dim.width,
height: dim.height,
data: [
prefix + 'data:image/svg+xml;charset=utf8,',
strictEncodeURIComponent(res.data),
sufix
].join(''),
format: 'svg',
name: path.basename(file.path, '.svg')
};
buffer.push(dim);
});
}
};
var endStream = function() {
this.emit('data', new gutil.File({
contents: new Buffer(mustache.render(tpl, {
items: buffer
}), 'utf8'),
path: opts.styleName
}));
this.emit('end');
};
return new through(bufferContents, endStream);
};