UNPKG

845 BJavaScriptView Raw
1'use strict';
2
3var isSvg = require('is-svg');
4var SVGO = require('svgo');
5var through = require('through2');
6
7module.exports = function (opts) {
8 opts = opts || {};
9
10 return through.ctor({objectMode: true}, function (file, enc, cb) {
11 if (file.isNull()) {
12 cb(null, file);
13 return;
14 }
15
16 if (file.isStream()) {
17 cb(new Error('Streaming is not supported'));
18 return;
19 }
20
21 if (!isSvg(file.contents)) {
22 cb(null, file);
23 return;
24 }
25
26 try {
27 var svgo = new SVGO(opts);
28
29 svgo.optimize(file.contents.toString('utf8'), function (res) {
30 if (!res.data || !res.data.length) {
31 return;
32 }
33
34 res.data = res.data.replace(/&(?!amp;)/g, '&');
35 res.data = new Buffer(res.data);
36
37 file.contents = res.data;
38 });
39 } catch (err) {
40 err.fileName = file.path;
41 cb(err);
42 return;
43 }
44
45 cb(null, file);
46 });
47};