-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathcss-class-extractor.ts
More file actions
38 lines (34 loc) · 1.35 KB
/
css-class-extractor.ts
File metadata and controls
38 lines (34 loc) · 1.35 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
import * as css from "css";
import CssClassDefinition from "../../common/css-class-definition";
export default class CssClassExtractor {
/**
* @description Extracts class names from CSS AST
*/
public static extract(ast: css.Stylesheet): CssClassDefinition[] {
const classNameRegex = /[.](([\w-]|\\[@:/])+)/g;
const definitions: CssClassDefinition[] = [];
// go through each of the selectors of the current rule
const addRule = (rule: css.Rule) => {
rule.selectors?.forEach((selector: string) => {
let item: RegExpExecArray | null = classNameRegex.exec(selector);
while (item) {
definitions.push(new CssClassDefinition(item[1].replace("\\", "")));
item = classNameRegex.exec(selector);
}
});
};
// go through each of the rules or media query...
ast.stylesheet?.rules.forEach((rule: css.Rule & css.Media) => {
// ...of type rule
if (rule.type === "rule") {
addRule(rule);
}
// of type media queries
if (rule.type === "media") {
// go through rules inside media queries
rule.rules?.forEach((rule: css.Rule) => addRule(rule));
}
});
return definitions;
}
}