forked from laptou/astro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
css.ts
46 lines (37 loc) Β· 1.57 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
import type vite from '../vite';
import path from 'path';
import { viteID } from '../util.js';
// https://vitejs.dev/guide/features.html#css-pre-processors
export const STYLE_EXTENSIONS = new Set(['.css', '.pcss', '.postcss', '.scss', '.sass', '.styl', '.stylus', '.less']);
const cssRe = new RegExp(
`\\.(${Array.from(STYLE_EXTENSIONS)
.map((s) => s.slice(1))
.join('|')})($|\\?)`
);
export const isCSSRequest = (request: string): boolean => cssRe.test(request);
/**
* getStylesForURL
* Given a filePath URL, crawl Viteβs module graph to find style files
*/
export function getStylesForURL(filePath: URL, viteServer: vite.ViteDevServer): Set<string> {
const css = new Set<string>();
// recursively crawl module graph to get all style files imported by parent id
function crawlCSS(id: string, scanned = new Set<string>()) {
// note: use .idToModuleMap() for lookups (.urlToModuleMap() may produce different
// URLs for modules depending on conditions, making resolution difficult)
const moduleName = viteServer.moduleGraph.idToModuleMap.get(id);
if (!moduleName || !moduleName.id) return;
scanned.add(moduleName.id);
// scan importedModules
for (const importedModule of moduleName.importedModules) {
if (!importedModule.id || scanned.has(importedModule.id)) continue;
const ext = path.extname(importedModule.url.toLowerCase());
if (STYLE_EXTENSIONS.has(ext)) {
css.add(importedModule.url); // note: return `url`s for HTML (not .id, which will break Windows)
}
crawlCSS(importedModule.id, scanned);
}
}
crawlCSS(viteID(filePath));
return css;
}