-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader.mjs
65 lines (49 loc) · 1.52 KB
/
loader.mjs
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
import fs from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import parseCSS from 'css-parse';
const { values: { loadFullStyles } } = parseArgs({
options: {
loadFullStyles: { type: 'boolean' },
},
});
export async function resolve(specifier, context, next) {
const nextResult = await next(specifier, context);
if (!specifier.endsWith('.css')) return nextResult;
return {
format: 'css',
shortCircuit: true,
url: nextResult.url,
};
}
export async function load(url, context, next) {
if (context.format !== 'css') return next(url, context);
const rawSource = '' + await fs.readFile(fileURLToPath(url));
const parsed = parseCssToObject(rawSource);
return {
format: 'json',
shortCircuit: true,
source: JSON.stringify(parsed),
};
}
function parseCssToObject(rawSource) {
const output = {};
for (const rule of parseCSS(rawSource).stylesheet.rules) {
let selector = rule['selectors'].at(-1); // Get right-most in the selector rule: `.Bar` in `.Foo > .Bar {…}`
if (selector[0] !== '.') break; // only care about classes
selector = selector
.substr(1) // Skip the initial `.`
.match(/(\w+)/)[1]; // Get only the classname: `Qux` in `.Qux[type="number"]`
output[selector] = loadFullStyles
? getClassStyles(rule['declarations'])
: selector;
}
return output;
}
function getClassStyles(declarations) {
const styles = {};
for (const declaration of declarations) {
styles[declaration['property']] = declaration['value'];
}
return styles;
}