-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcss.ts
50 lines (42 loc) · 1.58 KB
/
css.ts
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
import type { ViteDevServer } from "vite";
// cf
// https://github.com/hi-ogawa/vite-plugins/blob/3c496fa1bb5ac66d2880986877a37ed262f1d2a6/packages/vite-glob-routes/examples/demo/vite-plugin-ssr-css.ts
// https://github.com/remix-run/remix/blob/dev/packages/remix-dev/vite/styles.ts
export async function collectStyle(server: ViteDevServer, entries: string[]) {
const urls = await collectStyleUrls(server, entries);
const styles = await Promise.all(
urls.map(async (url) => {
const res = await server.transformRequest(url + "?direct");
return res?.code;
}),
);
return styles.filter(Boolean).join("\n\n");
}
export async function collectStyleUrls(
server: ViteDevServer,
entries: string[],
) {
const visited = new Set<string>();
async function traverse(url: string) {
const [, id] = await server.moduleGraph.resolveUrl(url);
if (visited.has(id)) {
return;
}
visited.add(id);
const mod = server.moduleGraph.getModuleById(id);
if (!mod) {
return;
}
await Promise.all(
[...mod.importedModules].map((childMod) => traverse(childMod.url)),
);
}
// ensure import analysis is ready for top entries
await Promise.all(entries.map((e) => server.transformRequest(e)));
// traverse
await Promise.all(entries.map((url) => traverse(url)));
return [...visited].filter((url) => url.match(CSS_LANGS_RE));
}
// cf. https://github.com/vitejs/vite/blob/d6bde8b03d433778aaed62afc2be0630c8131908/packages/vite/src/node/constants.ts#L49C23-L50
const CSS_LANGS_RE =
/\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;