-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathprocessSvg.js
58 lines (52 loc) · 1.35 KB
/
processSvg.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
const Svgo = require('svgo');
const cheerio = require('cheerio')
/**
* Convert string to CamelCase.
* @param {string} str - A string.
* @returns {string}
*/
function CamelCase(str) {
return str.replace(/(^|-)([a-z])/g, (_, __, c) => c.toUpperCase())
}
/**
* Optimize SVG with `svgo`.
* @param {string} svg - An SVG string.
* @returns {Promise<string>}
*/
function optimize(svg) {
const svgo = new Svgo({
plugins: [
{ convertShapeToPath: false },
{ mergePaths: false },
{ removeAttrs: { attrs: '(fill|stroke.*)' } },
{ removeTitle: true },
],
});
return new Promise(resolve => {
svgo.optimize(svg).then(({ data }) => resolve(data));
});
}
/**
* remove SVG element.
* @param {string} svg - An SVG string.
* @returns {string}
*/
function removeSVGElement(svg) {
const $ = cheerio.load(svg);
return $('body').children().html();
}
/**
* Process SVG string.
* @param {string} svg - An SVG string.
* @param {Promise<string>}
*/
async function processSvg(svg) {
const optimized = await optimize(svg)
// remove semicolon inserted by prettier
// because prettier thinks it's formatting JSX not HTML
.then(svg => svg.replace(/;/g, ''))
.then(removeSVGElement)
.then(svg => svg.replace(/([a-z]+)-([a-z]+)=/g, (_, a, b) => `${a}${CamelCase(b)}=`))
return optimized;
}
module.exports = processSvg;