-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathoptimize.js
59 lines (49 loc) · 1.59 KB
/
optimize.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
// validates svgo opts
// to contain minimal set of plugins that will strip some stuff
// for the babylon JSX parser to work
import * as SVGO from 'svgo';
import isPlainObject from 'lodash.isplainobject';
const essentialPlugins = ['removeDoctype', 'removeComments'];
function isEssentialPlugin(p) {
return essentialPlugins.indexOf(p) !== -1;
}
function validateAndFix(opts) {
if (!isPlainObject(opts)) return;
if (opts.full) {
if (
typeof opts.plugins === 'undefined'
|| (Array.isArray(opts.plugins) && opts.plugins.length === 0)
) {
/* eslint no-param-reassign: 1 */
opts.plugins = [...essentialPlugins];
return;
}
}
// opts.full is false, plugins can be empty
if (typeof opts.plugins === 'undefined') return;
if (Array.isArray(opts.plugins) && opts.plugins.length === 0) return;
// track whether its defined in opts.plugins
const state = essentialPlugins.reduce((p, c) => Object.assign(p, { [c]: false }), {});
opts.plugins.forEach((p) => {
if (typeof p === 'string' && isEssentialPlugin(p)) {
state[p] = true;
} else if (typeof p === 'object') {
Object.keys(p).forEach((k) => {
if (isEssentialPlugin(k)) {
// make it essential
if (!p[k]) p[k] = true;
// and update state
/* eslint no-param-reassign: 1 */
state[k] = true;
}
});
}
});
Object.keys(state)
.filter((key) => !state[key])
.forEach((key) => opts.plugins.push(key));
}
export default function optimize(content, opts = {}) {
validateAndFix(opts);
return SVGO.optimize(content, opts);
}