-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
optimize-svg.js
50 lines (42 loc) · 1012 Bytes
/
optimize-svg.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
import Svgo from 'svgo';
import cheerio from 'cheerio';
import DEFAULT_ATTRS from '../src/default-attrs.json';
/**
* Optimize SVG string.
* @param {string} svg - An SVG string.
* @returns {Promise<string>}
*/
function optimizeSvg(svg) {
return svgo(svg).then(setAttrs);
}
/**
* Run SVGO on SVG string.
* @param {string} svg - An SVG string.
* @returns {Promise<string>}
*/
function svgo(svg) {
const s = new Svgo({
plugins: [
{ convertShapeToPath: false },
{ mergePaths: false },
{ removeAttrs: { attrs: '(fill|stroke.*)' } },
{ removeTitle: true },
],
});
return new Promise(resolve => {
s.optimize(svg, ({ data }) => resolve(data));
});
}
/**
* Set default attributes on SVG.
* @param {string} svg - An SVG string.
* @returns {string}
*/
function setAttrs(svg) {
const $ = cheerio.load(svg);
Object.keys(DEFAULT_ATTRS).forEach(key =>
$('svg').attr(key, DEFAULT_ATTRS[key]),
);
return $('body').html();
}
export default optimizeSvg;