-
Notifications
You must be signed in to change notification settings - Fork 0
/
importCSSPreprocessor.js
59 lines (55 loc) · 1.89 KB
/
importCSSPreprocessor.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
import MagicString, {Bundle} from "magic-string";
import * as path from "path";
import * as fs from 'node:fs/promises';
/* Make `@import "./whatever.css" scoped;` statements import CSS into the component's CSS scope */
export default function importCSSPreprocess() {
async function importCSS({ content, filename }) {
function matchAllImports(str) {
const globalRegex = /@import\s+(".*"|'.*')\s+scoped\s*;/g;
const matches = [];
let match;
while ((match = globalRegex.exec(str)) !== null) {
const start = match.index;
const end = start + match[0].length;
matches.push({ start, end, file: match[1].substring(1, match[1].length - 1) });
}
return matches;
}
const imports = matchAllImports(content);
if(imports.length > 0) {
let lastStart = null;
const state = new MagicString(content, { filename });
const remove = (start, end) => state.clone().remove(start, end);
let out = [];
const deps = [];
for(const { start, end, file } of imports.reverse()) {
// Right
if(lastStart != null) {
out.push(remove(lastStart, content.length).remove(0, end));
} else {
out.push(remove(0, end));
}
const absPath = path.join(path.dirname(filename), file);
deps.push(absPath);
const text = (await fs.readFile(absPath)).toString();
out.push(new MagicString(text, { filename: absPath }));
lastStart = start;
}
// Left
const first = remove(lastStart, content.length);
const bundle = new Bundle();
bundle.addSource(first);
for(let i = out.length - 1; i >= 0; i--) {
bundle.addSource(out[i]);
}
return {
code: bundle.toString(),
map: bundle.generateMap(),
dependencies: deps
};
} else {
return {code: content};
}
}
return { style: importCSS }
}