fix(vite): serve css imported in islands (#3272)

Fixes https://github.com/denoland/fresh/issues/3271
This commit is contained in:
Marvin Hagemeister
2025-08-29 14:30:00 +02:00
committed by GitHub
parent b2c4f049bc
commit b41c151de3
14 changed files with 108 additions and 25 deletions
+2 -1
View File
@@ -102,7 +102,8 @@
"base", "base",
"noscript", "noscript",
"template" "template"
] ],
"types": ["./global.d.ts"]
}, },
"lint": { "lint": {
"rules": { "rules": {
Vendored
+4
View File
@@ -0,0 +1,4 @@
declare module "*.module.css" {
const CssMod: Record<string, string>;
export default CssMod;
}
+2
View File
@@ -97,6 +97,7 @@ export class IslandPreparer {
mod: Record<string, unknown>, mod: Record<string, unknown>,
chunkName: string, chunkName: string,
modName: string, modName: string,
css: string[],
) { ) {
for (const [name, value] of Object.entries(mod)) { for (const [name, value] of Object.entries(mod)) {
if (typeof value !== "function") continue; if (typeof value !== "function") continue;
@@ -110,6 +111,7 @@ export class IslandPreparer {
file: chunkName, file: chunkName,
fn, fn,
name: uniqueName, name: uniqueName,
css,
}); });
} }
} }
+1
View File
@@ -33,6 +33,7 @@ export interface Island {
name: string; name: string;
exportName: string; exportName: string;
fn: ComponentType; fn: ComponentType;
css: string[];
} }
export type ServerIslandRegistry = Map<ComponentType, Island>; export type ServerIslandRegistry = Map<ComponentType, Island>;
+1
View File
@@ -314,6 +314,7 @@ export class Builder<State = any> {
name, name,
server: spec, server: spec,
browser: null, browser: null,
css: [],
}); });
} }
+4 -2
View File
@@ -27,6 +27,7 @@ export interface IslandModChunk {
name: string; name: string;
server: string; server: string;
browser: string | null; browser: string | null;
css: string[];
} }
export type FsRouteFileNoMod<State> = Omit<FsRouteFile<State>, "mod"> & { export type FsRouteFileNoMod<State> = Omit<FsRouteFile<State>, "mod"> & {
@@ -206,7 +207,7 @@ export class MemoryBuildCache<State> implements DevBuildCache<State> {
throw new Error(`Unexpected missing browser chunk`); throw new Error(`Unexpected missing browser chunk`);
} }
preparer.prepare(this.islandRegistry, mod, chunk.browser, name); preparer.prepare(this.islandRegistry, mod, chunk.browser, name, []);
}, },
), ),
); );
@@ -461,7 +462,8 @@ export async function generateSnapshotServer(
const islandMarkers = islands.map((item) => { const islandMarkers = islands.map((item) => {
const browser = JSON.stringify(item.browser); const browser = JSON.stringify(item.browser);
const name = JSON.stringify(item.name); const name = JSON.stringify(item.name);
return `islandPreparer.prepare(islands, ${item.name}, ${browser}, ${name});`; const css = JSON.stringify(item.css);
return `islandPreparer.prepare(islands, ${item.name}, ${browser}, ${name}, ${css});`;
}).join("\n"); }).join("\n");
const serializedFsRoutes = fsRoutesFiles const serializedFsRoutes = fsRoutesFiles
@@ -254,8 +254,9 @@ options[OptionsType.DIFF] = (vnode) => {
RENDER_STATE!.renderedHtmlHead = true; RENDER_STATE!.renderedHtmlHead = true;
const entryAssets = RENDER_STATE.buildCache.getEntryAssets(); const entryAssets = RENDER_STATE.buildCache.getEntryAssets();
// deno-lint-ignore no-explicit-any
const items: VNode<any>[] = [];
if (entryAssets.length > 0) { if (entryAssets.length > 0) {
const items: VNode[] = [];
for (let i = 0; i < entryAssets.length; i++) { for (let i = 0; i < entryAssets.length; i++) {
const id = entryAssets[i]; const id = entryAssets[i];
@@ -266,32 +267,22 @@ options[OptionsType.DIFF] = (vnode) => {
); );
} }
} }
if (Array.isArray(vnode.props.children)) {
vnode.props.children.push(...items);
} else if (
vnode.props.children !== null &&
typeof vnode.props.children === "object"
) {
// deno-lint-ignore no-explicit-any
items.push(vnode.props.children as any);
vnode.props.children = items;
} else {
vnode.props.children = items;
}
} }
// Append component to render remaining head nodes // deno-lint-ignore no-explicit-any
const remaining = h(RemainingHead, null); items.push(h(RemainingHead, null) as VNode<any>);
if (Array.isArray(vnode.props.children)) { if (Array.isArray(vnode.props.children)) {
vnode.props.children.push(remaining); vnode.props.children.push(...items);
} else if ( } else if (
vnode.props.children !== null && vnode.props.children !== null &&
typeof vnode.props.children === "object" typeof vnode.props.children === "object"
) { ) {
vnode.props.children = [vnode.props.children, remaining]; // deno-lint-ignore no-explicit-any
items.unshift(vnode.props.children as any);
vnode.props.children = items;
} else { } else {
vnode.props.children = remaining; vnode.props.children = items;
} }
break; break;
@@ -412,8 +403,25 @@ options[OptionsType.DIFFED] = (vnode) => {
}; };
function RemainingHead() { function RemainingHead() {
if (RENDER_STATE !== null && RENDER_STATE.headComponents.size > 0) { if (RENDER_STATE !== null) {
return h(Fragment, null, ...RENDER_STATE.headComponents.values()); // deno-lint-ignore no-explicit-any
const items: VNode<any>[] = [];
if (RENDER_STATE.headComponents.size > 0) {
items.push(...RENDER_STATE.headComponents.values());
}
RENDER_STATE.islands.forEach((island) => {
if (island.css.length > 0) {
for (let i = 0; i < island.css.length; i++) {
const css = island.css[i];
items.push(h("link", { rel: "stylesheet", href: css }));
}
}
});
if (items.length > 0) {
return h(Fragment, null, items);
}
} }
return null; return null;
} }
@@ -0,0 +1,3 @@
.root {
color: red;
}
@@ -0,0 +1,6 @@
// @ts-ignore upstream issue https://github.com/denoland/deno/issues/30560
import styles from "./CssModules.module.css";
export function CssModules() {
return <h1 class={styles.root}>red text</h1>;
}
@@ -0,0 +1,5 @@
import { CssModules } from "../../islands/CssModules.tsx";
export default function Page() {
return <CssModules />;
}
+2 -1
View File
@@ -10,7 +10,8 @@
}, },
"compilerOptions": { "compilerOptions": {
"jsx": "precompile", "jsx": "precompile",
"jsxImportSource": "preact" "jsxImportSource": "preact",
"types": ["../../global.d.ts"]
}, },
"tasks": { "tasks": {
"demo": "vite demo", "demo": "vite demo",
@@ -153,6 +153,7 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
name: def.name, name: def.name,
server: id, server: id,
browser: def.chunk ?? `/@id/fresh-island::${def.name}`, browser: def.chunk ?? `/@id/fresh-island::${def.name}`,
css: [],
}; };
}); });
} else { } else {
@@ -206,11 +207,14 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
spec = spec.slice(1); spec = spec.slice(1);
} }
const chunkCss = mod.css?.map((id) => `/${id}`) ?? [];
const name = namer.getUniqueName(specToName(id)); const name = namer.getUniqueName(specToName(id));
islandMods.push({ islandMods.push({
name, name,
browser: spec, browser: spec,
server: serverPath, server: serverPath,
css: chunkCss,
}); });
} }
} }
+24
View File
@@ -326,3 +326,27 @@ Deno.test({
sanitizeOps: false, sanitizeOps: false,
sanitizeResources: false, sanitizeResources: false,
}); });
Deno.test({
name: "vite build - island css modules",
fn: async () => {
await launchProd(
{ cwd: viteResult.tmp },
async (address) => {
await withBrowser(async (page) => {
await page.goto(`${address}/tests/css_modules`, {
waitUntil: "networkidle2",
});
const color = await page
.locator("h1")
// deno-lint-ignore no-explicit-any
.evaluate((el) => window.getComputedStyle(el as any).color);
expect(color).toEqual("rgb(255, 0, 0)");
});
},
);
},
sanitizeOps: false,
sanitizeResources: false,
});
@@ -268,3 +268,24 @@ Deno.test({
sanitizeResources: false, sanitizeResources: false,
sanitizeOps: false, sanitizeOps: false,
}); });
Deno.test({
name: "vite dev - island css modules",
fn: async () => {
await launchDevServer(tmp.dir, async (address) => {
await withBrowser(async (page) => {
await page.goto(`${address}/tests/css_modules`, {
waitUntil: "networkidle2",
});
const color = await page
.locator("h1")
// deno-lint-ignore no-explicit-any
.evaluate((el) => window.getComputedStyle(el as any).color);
expect(color).toEqual("rgb(255, 0, 0)");
});
});
},
sanitizeResources: false,
sanitizeOps: false,
});