Skip to content

Commit

Permalink
fix(vite): fail to load components in the directory above package root (
Browse files Browse the repository at this point in the history
  • Loading branch information
AsPulse authored Nov 15, 2023
1 parent 4b5a538 commit 4b23472
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/eight-ladybugs-speak.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kuma-ui/vite": minor
---

Hot Reload no longer cause unnecessary full reloads.
5 changes: 5 additions & 0 deletions .changeset/slow-buttons-fold.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kuma-ui/vite": patch
---

Fixed a problem where KumaUI could not resolve CSS paths when importing files not in the package.
29 changes: 15 additions & 14 deletions packages/vite/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ export default function kumaUI(): Plugin {
}
}

const cssLookup: { [key: string]: string } = {};
const cssTable: {
url: string;
css: string;
}[] = [];
const virtualModuleId = "virtual:kuma-ui";

const userTheme = theme.getUserTheme();
Expand All @@ -62,31 +65,29 @@ export default function kumaUI(): Plugin {
const result = transform(code, id);
if (!result?.code) return;
const css = (result.metadata as unknown as { css: string }).css || "";
const cssFilename = path.normalize(
`${id.replace(/\.[jt]sx?$/, "")}-${generateHash(css)}.css`,
);
const cssRelativePath = path
.relative(process.cwd(), cssFilename)
.replace(/\\/g, path.posix.sep);
cssLookup[cssRelativePath] = css;
const cssPath = path.normalize(id.replace(/\.[jt]sx?$/, ""));
const url = `${virtualModuleId}/${generateHash(
path.dirname(cssPath),
)}/${path.basename(cssPath)}-${generateHash(css)}.css`;
cssTable.push({ url, css });

sheet.reset();
return (
`import "${virtualModuleId}/${cssRelativePath}";
`import "${url}";
` + result.code
);
},
load(url) {
if (!url.startsWith(`\0${virtualModuleId}`)) return undefined;
const id = url.slice(`\0${virtualModuleId}`.length + 1);
return cssLookup[id];
const urlContent = url.slice(`\0`.length);
return cssTable.find((c) => c.url === urlContent)?.css ?? undefined;
},
resolveId(importeeUrl) {
if (!importeeUrl.startsWith(virtualModuleId)) return undefined;
return `\0${importeeUrl}`;
},
handleHotUpdate({ server }) {
sheet.reset();
server.ws.send({ type: "full-reload" });
handleHotUpdate() {
cssTable.length = 0;
},
configResolved(config) {
if (config.define && Object.keys(config.define).length > 0) {
Expand Down

0 comments on commit 4b23472

Please sign in to comment.