From 7ce6aeff8b15b5f80e84e85dfc717b667989192c Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Fri, 12 Sep 2025 12:34:23 +0200 Subject: [PATCH] fix(vite): workaround for FOUC with tailwind (#3407) Fixes https://github.com/denoland/fresh/issues/3379 --- packages/plugin-vite/deno.json | 3 +- packages/plugin-vite/src/client.ts | 19 +++++ .../plugin-vite/src/plugins/client_entry.ts | 16 +--- .../plugin-vite/src/plugins/dev_server.ts | 84 ++++++++++++++++++- packages/plugin-vite/src/shared.ts | 12 +++ 5 files changed, 119 insertions(+), 15 deletions(-) create mode 100644 packages/plugin-vite/src/client.ts create mode 100644 packages/plugin-vite/src/shared.ts diff --git a/packages/plugin-vite/deno.json b/packages/plugin-vite/deno.json index e06f6b0c..6b7b843d 100644 --- a/packages/plugin-vite/deno.json +++ b/packages/plugin-vite/deno.json @@ -3,7 +3,8 @@ "version": "1.0.1", "license": "MIT", "exports": { - ".": "./src/mod.ts" + ".": "./src/mod.ts", + "./client": "./src/client.ts" }, "publish": { "include": ["./src", "README.md"] diff --git a/packages/plugin-vite/src/client.ts b/packages/plugin-vite/src/client.ts new file mode 100644 index 00000000..71424e2c --- /dev/null +++ b/packages/plugin-vite/src/client.ts @@ -0,0 +1,19 @@ +import type { UpdatePayload } from "vite"; +import { hashCode } from "./shared.ts"; + +if (import.meta.hot) { + import.meta.hot.on("fresh:reload", () => { + window.location.reload(); + }); + + import.meta.hot.on("vite:beforeUpdate", (module: UpdatePayload) => { + module.updates.forEach((update) => { + const moduleStyle = document.querySelector( + `[vite-module-id="${hashCode(update.acceptedPath)}"]`, + ); + if (moduleStyle) { + moduleStyle.remove(); + } + }); + }); +} diff --git a/packages/plugin-vite/src/plugins/client_entry.ts b/packages/plugin-vite/src/plugins/client_entry.ts index c1501909..cc806d55 100644 --- a/packages/plugin-vite/src/plugins/client_entry.ts +++ b/packages/plugin-vite/src/plugins/client_entry.ts @@ -21,11 +21,13 @@ export function clientEntryPlugin(options: ResolvedFreshViteConfig): Plugin { }, resolveId: { filter: { - id: /(fresh:client-entry|fresh:client-entry-user)/, + id: /(fresh:client-entry|fresh:client-entry-user|fresh:client-quirks)/, }, handler(id) { if (id === modName) { return `\0${modName}`; + } else if (id === "fresh:client-quirks") { + return "@fresh/plugin-vite/client"; } else if (id === modNameUser) { return clientEntry; } @@ -48,17 +50,7 @@ export function clientEntryPlugin(options: ResolvedFreshViteConfig): Plugin { ${isDev ? 'import "preact/debug"' : ""} export * from "fresh/runtime-client"; ${exists ? `import "fresh:client-entry-user";` : ""} - -if (import.meta.hot) { - import.meta.hot.accept(() => { - console.log("accepting") - }); - import.meta.hot.on("fresh:reload", ev => { - console.log(ev) - window.location.reload(); - }); -} -`; +import "@fresh/plugin-vite/client";`; }, }, }; diff --git a/packages/plugin-vite/src/plugins/dev_server.ts b/packages/plugin-vite/src/plugins/dev_server.ts index 90d36a26..652da302 100644 --- a/packages/plugin-vite/src/plugins/dev_server.ts +++ b/packages/plugin-vite/src/plugins/dev_server.ts @@ -1,7 +1,8 @@ -import type { Plugin } from "vite"; +import type { DevEnvironment, Plugin } from "vite"; import * as path from "@std/path"; import { ASSET_CACHE_BUST_KEY } from "fresh/internal"; import { createRequest, sendResponse } from "@mjackson/node-fetch-server"; +import { hashCode } from "../shared.ts"; export function devServer(): Plugin[] { let publicDir = ""; @@ -71,7 +72,33 @@ export function devServer(): Plugin[] { try { const req = createRequest(nodeReq, nodeRes); - const res = await mod.default.fetch(req); + const res = (await mod.default.fetch(req)) as Response; + + // Collect css eagerly to avoid FOUC. This is a workaround for + // Vite not supporting css natively. It's a bit hacky, but + // gets the job done. + if ( + url.pathname !== "/__inspect" && + res.headers.get("Content-Type")?.includes("text/html") + ) { + const collected = await collectCss2( + "fresh:client-entry", + server.environments.client, + ); + + let html = await res.text(); + + const styles = collected.join("\n"); + html = html.replace("", styles + ""); + + const newRes = new Response(html, { + status: res.status, + headers: res.headers, + }); + await sendResponse(nodeRes, newRes); + return; + } + await sendResponse(nodeRes, res); } catch (err) { return next(err); @@ -104,3 +131,56 @@ export function devServer(): Plugin[] { }, ]; } + +async function collectCss2( + id: string, + env: DevEnvironment, +) { + const seen = new Set(); + const queue: string[] = [id]; + const out: string[] = []; + + let current: string | undefined; + while ((current = queue.pop()) !== undefined) { + if (seen.has(current)) continue; + seen.add(current); + + let mod = env.moduleGraph.idToModuleMap.get(current); + if (mod === undefined || mod.transformResult === null) { + // During development assets are loaded lazily, so we need + // to trigger processing manually. + await env.fetchModule(current); + mod = env.moduleGraph.idToModuleMap.get(current) ?? + env.moduleGraph.idToModuleMap.get(`\0${current}`); + + if (mod === undefined) continue; + } + + if ( + (current.endsWith(".scss") || + current.endsWith(".css")) && mod.transformResult + ) { + // Since vite stores everything as a JS file we need to + // extract the CSS out of the JS + const match = mod.transformResult.code.match( + /__vite__css\s+=\s+("(?:\\\\|\\"|[^"])*")/, + ); + + if (match !== null) { + const content = JSON.parse(match[1]); + out.push( + ``, + ); + } + } + + mod.importedModules.forEach((m) => { + if (m.id === null) return; + queue.push(m.id); + }); + } + + return out; +} diff --git a/packages/plugin-vite/src/shared.ts b/packages/plugin-vite/src/shared.ts new file mode 100644 index 00000000..927a3d40 --- /dev/null +++ b/packages/plugin-vite/src/shared.ts @@ -0,0 +1,12 @@ +export function hashCode(moduleId: string) { + let hash = 0, + i, + chr; + if (moduleId.length === 0) return hash; + for (i = 0; i < moduleId.length; i++) { + chr = moduleId.charCodeAt(i); + hash = (hash << 5) - hash + chr; + hash |= 0; // Convert to 32bit integer + } + return hash; +}