Skip to content

Commit 60e8041

Browse files
authored
fix CSS HMR for Vite virtual modules (#477)
1 parent f90c65b commit 60e8041

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

.changeset/mighty-banks-argue.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"next-yak": patch
3+
---
4+
5+
fix HMR for CSS in Vite

packages/next-yak/loaders/vite-plugin.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,25 @@ export async function viteYak(
279279
}
280280
},
281281
},
282+
283+
// Vite's default HMR only updates the JS module when a source file changes.
284+
// The extracted CSS lives in a separate virtual module (virtual:yak-css:...)
285+
// which Vite doesn't know is derived from the source file. Without explicit
286+
// invalidation here, the browser keeps stale CSS after edits.
287+
hotUpdate({ modules, file, type }) {
288+
if (type !== "update" && type !== "create") return;
289+
if (!sourceFileRegex.test(file)) return;
290+
291+
// The SWC plugin generates virtual module paths relative to root
292+
// (via {{__MODULE_PATH__}}), so we must match that format.
293+
const relativePath = relative(root, file);
294+
const virtualId = "\0virtual:yak-css:" + relativePath + ".css";
295+
const mod = this.environment.moduleGraph.getModuleById(virtualId);
296+
if (mod) {
297+
this.environment.moduleGraph.invalidateModule(mod);
298+
return [...modules, mod];
299+
}
300+
},
282301
};
283302
}
284303

0 commit comments

Comments
 (0)