Open History to see the last commit
1/**
2 * CSS collection for dev mode.
3 * Crawls the Vite module graph to collect CSS from the router entry and all its dependencies.
4 */
5import path from 'node:path'
6import type { ModuleNode, ViteDevServer } from 'vite'
7β
8// CSS file extensions supported by Vite
9const CSS_FILE_REGEX =
10 /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/
11// CSS modules file pattern - exported for use in plugin hook filters
12// Note: allow query/hash suffix since Vite ids often include them.
13export const CSS_MODULES_REGEX =
14 /\.module\.(css|less|sass|scss|styl|stylus)(?:$|[?#])/i
15β
16export function normalizeCssModuleCacheKey(idOrFile: string): string {
17 const baseId = idOrFile.split('?')[0]!.split('#')[0]!
18 return baseId.replace(/\\/g, '/')
19}
20// URL params that indicate CSS should not be injected (e.g., ?url, ?inline)
21const CSS_SIDE_EFFECT_FREE_PARAMS = ['url', 'inline', 'raw', 'inline-css']
22β
23// Marker to find the CSS string in Vite's transformed output
24const VITE_CSS_MARKER = 'const __vite__css = '
25β
26const ESCAPE_CSS_COMMENT_START_REGEX = /\/\*/g
27const ESCAPE_CSS_COMMENT_END_REGEX = /\*\//g
28β
29function isCssFile(file: string): boolean {
30 return CSS_FILE_REGEX.test(file)
31}
32β
33export function isCssModulesFile(file: string): boolean {
34 return CSS_MODULES_REGEX.test(file)
35}
36β
37function hasCssSideEffectFreeParam(url: string): boolean {
38 const queryString = url.split('?')[1]
39 if (!queryString) return false
40β
41 const params = new URLSearchParams(queryString)
42 return CSS_SIDE_EFFECT_FREE_PARAMS.some(
43 (param) =>
44 params.get(param) === '' &&
45 !url.includes(`?${param}=`) &&
46 !url.includes(`&${param}=`),
47 )
48}
49β
50/**
51 * Resolve a file path to a Vite dev server URL.
52 * Files within the root directory use relative paths, files outside use /@fs prefix.
53 */
54function resolveDevUrl(rootDirectory: string, filePath: string): string {
55 const normalizedPath = filePath.replace(/\\/g, '/')
56 const relativePath = path.posix.relative(
57 rootDirectory.replace(/\\/g, '/'),
58 normalizedPath,
59 )
60 const isWithinRoot =
61 !relativePath.startsWith('..') && !path.isAbsolute(relativePath)
62β
63 if (isWithinRoot) {
64 return path.posix.join('/', relativePath)
65 }
66 // Files outside root need /@fs prefix
67 return path.posix.join('/@fs', normalizedPath)
68}
69β
70export interface CollectDevStylesOptions {
71 viteDevServer: ViteDevServer
72 entries: Array<string>
73 /** Cache of CSS modules content captured during transform hook */
74 cssModulesCache?: Record<string, string>
75}
76β
77/**
78 * Collect CSS content from the module graph starting from the given entry points.
79 */
80export async function collectDevStyles(
81 opts: CollectDevStylesOptions,
82): Promise<string | undefined> {
83 const { viteDevServer, entries, cssModulesCache = {} } = opts
84 const styles: Map<string, string> = new Map()
85 const visited = new Set<ModuleNode>()
86β
87 const rootDirectory = viteDevServer.config.root
88β
89 // Process entries in parallel - each entry is independent
90 await Promise.all(
91 entries.map((entry) =>
92 processEntry(viteDevServer, resolveDevUrl(rootDirectory, entry), visited),
93 ),
94 )
95β
96 // Collect CSS from visited modules in parallel
97 const cssPromises: Array<Promise<readonly [string, string] | null>> = []
98β
99 for (const dep of visited) {
100 if (hasCssSideEffectFreeParam(dep.url)) {
101 continue
102 }
103β
104 if (dep.file && isCssModulesFile(dep.file)) {
105 const css = cssModulesCache[normalizeCssModuleCacheKey(dep.file)]
106 if (!css) {
107 // skip this module - it may not be a real CSS module or it may not have been transformed yet
108 continue
109 }
110 styles.set(dep.url, css)
111 continue
112 }
113β
114 const fileOrUrl = dep.file ?? dep.url
115 if (!isCssFile(fileOrUrl)) {
116 continue
117 }
118β
119 // Load regular CSS files in parallel
120 cssPromises.push(
121 fetchCssFromModule(viteDevServer, dep).then((css) =>
122 css ? ([dep.url, css] as const) : null,
123 ),
124 )
125 }
126β
127 // Wait for all CSS loads to complete
128 const cssResults = await Promise.all(cssPromises)
129 for (const result of cssResults) {
130 if (result) {
131 styles.set(result[0], result[1])
132 }
133 }
134β
135 if (styles.size === 0) return undefined
136β
137 const parts: Array<string> = []
138 for (const [fileName, css] of styles.entries()) {
139 const escapedFileName = fileName
140 .replace(ESCAPE_CSS_COMMENT_START_REGEX, '/\\*')
141 .replace(ESCAPE_CSS_COMMENT_END_REGEX, '*\\/')
142 parts.push(`\n/* ${escapedFileName} */\n${css}`)
143 }
144 return parts.join('\n')
145}
146β
147/**
148 * Process an entry URL: transform it if needed, get the module node, and crawl its dependencies.
149 */
150async function processEntry(
151 viteDevServer: ViteDevServer,
152 entryUrl: string,
153 visited: Set<ModuleNode>,
154): Promise<void> {
155 let node = await viteDevServer.moduleGraph.getModuleByUrl(entryUrl)
156β
157 // Only transform if not yet SSR-transformed (need ssrTransformResult.deps for crawling)
158 if (!node?.ssrTransformResult) {
159 try {
160 await viteDevServer.transformRequest(entryUrl)
161 } catch {
162 // ignore - module might not exist yet
163 }
164 node = await viteDevServer.moduleGraph.getModuleByUrl(entryUrl)
165 }
166β
167 if (!node || visited.has(node)) return
168β
169 visited.add(node)
170 await findModuleDeps(viteDevServer, node, visited)
171}
172β
173/**
174 * Find all module dependencies by crawling the module graph.
175 * Uses transformResult.deps for URL-based lookups (parallel) and
176 * importedModules for already-resolved nodes (parallel).
177 */
178async function findModuleDeps(
179 viteDevServer: ViteDevServer,
180 node: ModuleNode,
181 visited: Set<ModuleNode>,
182): Promise<void> {
183 // Note: caller must add node to visited BEFORE calling this function
184 // to prevent race conditions with parallel traversal
185β
186 // Process deps from transformResult if available (URLs including bare imports)
187 const deps =
188 node.ssrTransformResult?.deps ?? node.transformResult?.deps ?? null
189β
190 const importedModules = node.importedModules
191β
192 // Fast path: no deps and no imports
193 if ((!deps || deps.length === 0) && importedModules.size === 0) {
194 return
195 }
196β
197 // Build branches only when needed (avoid array allocation on leaf nodes)
198 const branches: Array<Promise<void>> = []
199β
200 if (deps) {
201 for (const depUrl of deps) {
202 const dep = await viteDevServer.moduleGraph.getModuleByUrl(depUrl)
203 if (!dep) continue
204β
205 if (visited.has(dep)) continue
206 visited.add(dep)
207 branches.push(findModuleDeps(viteDevServer, dep, visited))
208 }
209 }
210β
211 // ALWAYS also traverse importedModules - this catches:
212 // - Code-split chunks (e.g. ?tsr-split=component) not in deps
213 // - Already-resolved nodes
214 for (const depNode of importedModules) {
215 if (visited.has(depNode)) continue
216 visited.add(depNode)
217 branches.push(findModuleDeps(viteDevServer, depNode, visited))
218 }
219β
220 if (branches.length === 1) {
221 await branches[0]
222 return
223 }
224β
225 await Promise.all(branches)
226}
227β
228async function fetchCssFromModule(
229 viteDevServer: ViteDevServer,
230 node: ModuleNode,
231): Promise<string | undefined> {
232 // Use cached transform result if available
233 const cachedCode = node.transformResult?.code ?? node.ssrTransformResult?.code
234 if (cachedCode) {
235 return extractCssFromCode(cachedCode)
236 }
237β
238 // Otherwise request a fresh transform
239 try {
240 const transformResult = await viteDevServer.transformRequest(node.url)
241 if (!transformResult?.code) return undefined
242β
243 return extractCssFromCode(transformResult.code)
244 } catch {
245 // Preprocessor partials (e.g., Sass files with mixins) can't compile in isolation.
246 // The root stylesheet that @imports them will contain the compiled CSS.
247 return undefined
248 }
249}
250β
251/**
252 * Extract CSS content from Vite's transformed CSS module code.
253 *
254 * Vite embeds CSS into the module as a JS string via `JSON.stringify(cssContent)`,
255 * e.g. `const __vite__css = ${JSON.stringify('...css...')}`.
256 *
257 * We locate that JSON string literal and run `JSON.parse` on it to reverse the
258 * escaping (\\n, \\t, \\", \\\\, \\uXXXX, etc.).
259 */
260export function extractCssFromCode(code: string): string | undefined {
261 const startIdx = code.indexOf(VITE_CSS_MARKER)
262 if (startIdx === -1) return undefined
263β
264 const valueStart = startIdx + VITE_CSS_MARKER.length
265 // Vite emits `const __vite__css = ${JSON.stringify(cssContent)}` which always
266 // produces double-quoted JSON string literals.
267 if (code.charCodeAt(valueStart) !== 34) return undefined
268β
269 const codeLength = code.length
270 let i = valueStart + 1
271 while (i < codeLength) {
272 const charCode = code.charCodeAt(i)
273 // 34 = '"'
274 if (charCode === 34) {
275 try {
276 return JSON.parse(code.slice(valueStart, i + 1))
277 } catch {
278 return undefined
279 }
280 }
281 // 92 = '\\'
282 if (charCode === 92) {
283 i += 2
284 } else {
285 i++
286 }
287 }
288β
289 return undefined
290}