forked from w0rm/gulp-svgstore
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
61 lines (47 loc) · 2.08 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
var path = require('path');
var through2 = require('through2');
var gutil = require('gulp-util');
var cheerio = require('cheerio');
module.exports = function (config) {
config = config || {}
var prefix = config.prefix || '';
var fileName = config.fileName || 'svgstore.svg';
var inlineSvg = config.inlineSvg || false;
var transformSvg = config.transformSvg || false;
var combinedDoc = cheerio.load('<?xml version="1.0" encoding="UTF-8"?>' +
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' +
'<svg xmlns="http://www.w3.org/2000/svg"></svg>', { xmlMode: true });
var combinedSvg = combinedDoc('svg');
return through2.obj(
function transform(file, encoding, cb) {
if (file.isStream()) {
return cb(new gutil.PluginError('gulp-svgstore', 'Streams are not supported!'));
}
var idAttr = prefix + path.basename(file.relative, path.extname(file.relative));
var $xmlDoc = cheerio.load(file.contents.toString('utf8'), {xmlMode: true});
var viewBoxAttr = $xmlDoc('svg').attr('viewBox') || '';
var symbolDoc = cheerio.load('<symbol></symbol>', {xmlMode: true});
var symbol = symbolDoc('symbol');
symbol.attr({id: idAttr, viewBox: viewBoxAttr});
symbol.append($xmlDoc('svg').html());
combinedSvg.append(symbol);
cb(null);
}, function flush(cb) {
var self = this;
function done(err) {
var file;
var contents;
if (err) return cb(err);
contents = inlineSvg ? combinedSvg : combinedDoc;
file = new gutil.File({path: fileName, contents: new Buffer(contents.html())});
self.push(file);
cb(null);
}
if (transformSvg) {
transformSvg(combinedSvg, done);
} else {
done(null, combinedSvg);
}
}
)
}