extractICSS.js
1.67 KB
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
73
74
75
76
const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
const getDeclsObject = (rule) => {
const object = {};
rule.walkDecls((decl) => {
const before = decl.raws.before ? decl.raws.before.trim() : "";
object[before + decl.prop] = decl.value;
});
return object;
};
/**
*
* @param {string} css
* @param {boolean} removeRules
* @param {'auto' | 'rule' | 'at-rule'} mode
*/
const extractICSS = (css, removeRules = true, mode = "auto") => {
const icssImports = {};
const icssExports = {};
function addImports(node, path) {
const unquoted = path.replace(/'|"/g, "");
icssImports[unquoted] = Object.assign(
icssImports[unquoted] || {},
getDeclsObject(node)
);
if (removeRules) {
node.remove();
}
}
function addExports(node) {
Object.assign(icssExports, getDeclsObject(node));
if (removeRules) {
node.remove();
}
}
css.each((node) => {
if (node.type === "rule" && mode !== "at-rule") {
if (node.selector.slice(0, 7) === ":import") {
const matches = importPattern.exec(node.selector);
if (matches) {
addImports(node, matches[1]);
}
}
if (node.selector === ":export") {
addExports(node);
}
}
if (node.type === "atrule" && mode !== "rule") {
if (node.name === "icss-import") {
const matches = balancedQuotes.exec(node.params);
if (matches) {
addImports(node, matches[1]);
}
}
if (node.name === "icss-export") {
addExports(node);
}
}
});
return { icssImports, icssExports };
};
module.exports = extractICSS;