-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (50 loc) · 2.09 KB
/
index.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
'use strict';
const postcss = require('postcss');
const path = require('path');
const fs = require('fs-extra');
module.exports = postcss.plugin('postcss-split-css', (options) => {
options = options || {};
options.filter = options.filter || [];
let removeAtRules = ['font-face', 'import', 'keyframes'];
let pattern = new RegExp((options.filter.join("|")).replace(/\./g, '\\.'), 'g');
return (root) => {
if (options.filter.length) {
let newRoot = postcss.parse(root.toString());
newRoot.walkRules((rule) => {
let selectors = rule.selectors.filter((selector) => {
pattern.lastIndex = 0;
return pattern.test(selector);
});
if (selectors.length === 0) {
rule.parent.removeChild(rule);
} else {
rule.selectors = selectors;
}
});
newRoot.walkAtRules((rule) => {
let isEmpty = Array.isArray(rule.nodes) && rule.nodes.length === 0,
removeByDefault = removeAtRules.indexOf(rule.name) >= 0;
if (isEmpty || removeByDefault) {
rule.parent.removeChild(rule);
}
});
if (options.output) {
let filePath = path.join(options.output.dist, path.relative(options.output.from, root.source.input.file));
if (options.output.subfix) {
let ext = path.extname(filePath);
filePath = filePath.replace(ext, options.output.subfix + ext)
}
fs.outputFileSync(filePath, newRoot.toString() + (options.output.append || ''));
}
root.walkRules((rule) => {
let selectors = rule.selectors.filter((selector) => {
pattern.lastIndex = 0;
return pattern.test(selector);
});
if (selectors.length) {
rule.parent.removeChild(rule);
}
});
}
};
});