-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminifyStyles.js
executable file
·72 lines (57 loc) · 1.8 KB
/
minifyStyles.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
62
63
64
65
66
67
68
69
70
71
72
'use strict';
exports.type = 'perItem';
exports.active = true;
exports.params = {
svgo: {}
};
exports.description = 'minifies existing styles in svg';
var csso = require('csso');
// wraps css rules into a selector to make it parseable
var rulesToDummySelector = function(str) {
return '.dummy { ' + str + ' }';
};
// helper to extract css rules from full css selector
var extractRuleCss = function(str) {
var strEx = str.match(/\.dummy{(.*)}/i)[1];
return strEx;
};
// minifies css using csso
var minifyCss = function(css, options) {
return csso.minify(css, options);
};
/**
* Minifies styles (<style> element + style attribute) using svgo
*
* @param {Object} item current iteration item
* @return {Boolean} if false, item will be filtered out
*
* @author strarsis <[email protected]>
*/
exports.fn = function(item, svgoOptions) {
if(item.elem) {
if(item.isElem('style') && !item.isEmpty()) {
var styleCss = item.content[0].text || item.content[0].cdata || [],
DATA = styleCss.indexOf('>') >= 0 || styleCss.indexOf('<') >= 0 ? 'cdata' : 'text';
if(styleCss.length > 0) {
var styleCssMinified = minifyCss(styleCss, svgoOptions);
item.content[0][DATA] = styleCssMinified;
}
}
if(item.hasAttr('style')) {
var itemCss = item.attr('style').value;
if(itemCss.length > 0) {
var itemCssMinified =
extractRuleCss(
minifyCss(
rulesToDummySelector(
itemCss
),
svgoOptions
)
);
item.attr('style').value = itemCssMinified;
}
}
}
return item;
};