fix(vite): support ssr css modules (#3355)

Fixes https://github.com/denoland/fresh/issues/3325
This commit is contained in:
Marvin Hagemeister
2025-09-08 16:23:13 +02:00
committed by GitHub
parent 4c3ff9b74d
commit 2c32ffe8f3
11 changed files with 520 additions and 270 deletions
+5
View File
@@ -1,3 +1,4 @@
import { setAdditionalStyles } from "./context.ts";
import { HttpError } from "./error.ts"; import { HttpError } from "./error.ts";
import { isHandlerByMethod, type PageResponse } from "./handlers.ts"; import { isHandlerByMethod, type PageResponse } from "./handlers.ts";
import type { MaybeLazyMiddleware, Middleware } from "./middlewares/mod.ts"; import type { MaybeLazyMiddleware, Middleware } from "./middlewares/mod.ts";
@@ -282,6 +283,10 @@ function applyCommandsInner<State>(
def = await route(); def = await route();
} }
if (def.css !== undefined) {
setAdditionalStyles(ctx, def.css);
}
return renderRoute(ctx, def); return renderRoute(ctx, def);
}); });
+11
View File
@@ -52,6 +52,7 @@ export type FreshContext<State = unknown> = Context<State>;
export let getBuildCache: <T>(ctx: Context<T>) => BuildCache<T>; export let getBuildCache: <T>(ctx: Context<T>) => BuildCache<T>;
export let getInternals: <T>(ctx: Context<T>) => UiTree<unknown, T>; export let getInternals: <T>(ctx: Context<T>) => UiTree<unknown, T>;
export let setAdditionalStyles: <T>(ctx: Context<T>, css: string[]) => void;
/** /**
* The context passed to every middleware. It is unique for every request. * The context passed to every middleware. It is unique for every request.
@@ -116,6 +117,7 @@ export class Context<State> {
next: () => Promise<Response>; next: () => Promise<Response>;
#buildCache: BuildCache<State>; #buildCache: BuildCache<State>;
#additionalStyles: string[] | null = null;
Component!: FunctionComponent; Component!: FunctionComponent;
@@ -123,6 +125,8 @@ export class Context<State> {
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
getInternals = <T>(ctx: Context<T>) => ctx.#internal as any; getInternals = <T>(ctx: Context<T>) => ctx.#internal as any;
getBuildCache = <T>(ctx: Context<T>) => ctx.#buildCache; getBuildCache = <T>(ctx: Context<T>) => ctx.#buildCache;
setAdditionalStyles = <T>(ctx: Context<T>, css: string[]) =>
ctx.#additionalStyles = css;
} }
constructor( constructor(
@@ -280,6 +284,13 @@ export class Context<State> {
partialId, partialId,
); );
if (this.#additionalStyles !== null) {
for (let i = 0; i < this.#additionalStyles.length; i++) {
const css = this.#additionalStyles[i];
state.islandAssets.add(css);
}
}
try { try {
setRenderState(state); setRenderState(state);
+1
View File
@@ -91,6 +91,7 @@ export async function crawlRouteDir<State>(
pattern, pattern,
routePattern, routePattern,
lazy, lazy,
css: [],
overrideConfig, overrideConfig,
}); });
}, ignore); }, ignore);
+3
View File
@@ -25,6 +25,7 @@ export interface FreshFsMod<State> {
default?: default?:
| AnyComponent<PageProps<unknown, State>> | AnyComponent<PageProps<unknown, State>>
| AsyncAnyComponent<PageProps<unknown, State>>; | AsyncAnyComponent<PageProps<unknown, State>>;
css?: string[];
} }
export interface FsRouteFile<State> { export interface FsRouteFile<State> {
@@ -35,6 +36,7 @@ export interface FsRouteFile<State> {
type: CommandType; type: CommandType;
routePattern: string; routePattern: string;
overrideConfig: RouteConfig | undefined; overrideConfig: RouteConfig | undefined;
css: string[];
} }
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
@@ -334,5 +336,6 @@ function normalizeRoute<State>(
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
handler: (handlers as any) ?? undefined, handler: (handlers as any) ?? undefined,
component: mod.default, component: mod.default,
css: rawMod.css,
}; };
} }
+2
View File
@@ -56,6 +56,8 @@ export interface Route<State> {
component?: RouteComponent<State>; component?: RouteComponent<State>;
config?: RouteConfig; config?: RouteConfig;
handler?: RouteHandler<unknown, State>; handler?: RouteHandler<unknown, State>;
/** Additional .css files to load */
css?: string[];
} }
/** /**
@@ -0,0 +1,3 @@
.root {
color: peachpuff;
}
@@ -1,5 +1,14 @@
import { CssModules } from "../../islands/CssModules.tsx"; import { CssModules } from "../../islands/CssModules.tsx";
// @ts-ignore upstream issue https://github.com/denoland/deno/issues/30560
import styles from "./CssRoute.module.css";
export default function Page() { export default function Page() {
return <CssModules />; return (
<div>
<CssModules />
<div class="route">
<h1 class={styles.root}>peachpuff text</h1>
</div>
</div>
);
} }
@@ -102,6 +102,18 @@ if (import.meta.hot) import.meta.hot.accept();`;
}); });
} }
} }
if (item.css) {
for (let i = 0; i < item.css.length; i++) {
const id = item.css[i];
staticFiles.push({
filePath: path.join(serverOutDir, id),
hash: null,
pathname: `/${id}`,
});
}
}
} }
} }
@@ -7,6 +7,7 @@ import type {
import { import {
crawlFsItem, crawlFsItem,
fsAdapter, fsAdapter,
type FsRouteFileNoMod,
generateSnapshotServer, generateSnapshotServer,
type IslandModChunk, type IslandModChunk,
pathToSpec, pathToSpec,
@@ -29,14 +30,21 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
let server: ViteDevServer | undefined; let server: ViteDevServer | undefined;
let clientOutDir = ""; let clientOutDir = "";
let serverOutDir = "";
let root = ""; let root = "";
let publicDir = ""; let publicDir = "";
const islands = new Map<string, { name: string; chunk: string | null }>(); const islands = new Map<string, { name: string; chunk: string | null }>();
const islandsByFile = new Set<string>(); const islandsByFile = new Set<string>();
const islandSpecByName = new Map<string, string>(); const islandSpecByName = new Map<string, string>();
const routeNamer = new UniqueNamer();
const routeFileToName = new Map<string, string>();
return [{ // deno-lint-ignore no-explicit-any
const routes: Map<string, FsRouteFileNoMod<any>> = new Map();
return [
{
name: "fresh:server-snapshot", name: "fresh:server-snapshot",
applyToEnvironment(env) { applyToEnvironment(env) {
return env.name === "ssr"; return env.name === "ssr";
@@ -52,6 +60,10 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
config.environments.client.build.outDir, config.environments.client.build.outDir,
config.root, config.root,
); );
serverOutDir = pathWithRoot(
config.environments.ssr.build.outDir,
config.root,
);
options.islandSpecifiers.forEach((name, spec) => { options.islandSpecifiers.forEach((name, spec) => {
islands.set(spec, { name, chunk: null }); islands.set(spec, { name, chunk: null });
@@ -143,6 +155,14 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
islandsByFile.add(spec); islandsByFile.add(spec);
} }
for (let i = 0; i < result.routes.length; i++) {
const route = result.routes[i];
const name = routeNamer.getUniqueName(route.id);
routeFileToName.set(route.filePath, name);
routes.set(name, route);
}
const staticFiles: PendingStaticFile[] = []; const staticFiles: PendingStaticFile[] = [];
let islandMods: IslandModChunk[] = []; let islandMods: IslandModChunk[] = [];
let clientEntry = "/@id/fresh:client-entry"; let clientEntry = "/@id/fresh:client-entry";
@@ -305,6 +325,10 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
if (def) { if (def) {
return `fresh-island::${def.name}`; return `fresh-island::${def.name}`;
} }
const routeDef = routeFileToName.get(file);
if (routeDef !== undefined) {
return `fresh-route::${routeDef}`;
}
return path.toFileUrl(file).href; return path.toFileUrl(file).href;
}, },
}); });
@@ -312,7 +336,51 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
return code; return code;
}, },
}, },
}, { transform: {
filter: {
id: /\.module\.(css|less|sass)(\?.*)?$/,
},
handler(_code, id, _options) {
if (server) {
const ssrGraph = server.environments.ssr.moduleGraph;
const mod = ssrGraph.getModuleById(id);
if (mod === undefined) return;
const snapshot = ssrGraph.getModuleById("\0fresh:server-snapshot");
if (snapshot === undefined) return;
const queue: EnvironmentModuleNode[] = [mod];
let item: EnvironmentModuleNode | undefined;
while ((item = queue.pop()) !== undefined) {
if (item.file !== null) {
const normalized = path.normalize(item.file);
const name = routeFileToName.get(normalized);
if (name !== undefined) {
const route = routes.get(name);
if (route !== undefined) {
const mod = ssrGraph.getModuleById(id);
if (mod !== undefined) {
route.css.push(mod.url);
}
const routeMod = ssrGraph.getModuleById(
`\0fresh-route-css::${name}`,
);
if (routeMod !== undefined) {
ssrGraph.invalidateModule(routeMod);
}
}
}
}
item.importers.forEach((importer) => queue.push(importer));
}
}
},
},
},
{
name: "fresh:island-resolver", name: "fresh:island-resolver",
resolveId: { resolveId: {
filter: { filter: {
@@ -329,7 +397,122 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
if (spec !== undefined) return spec; if (spec !== undefined) return spec;
}, },
}, },
}]; },
{
name: "fresh:route-css",
resolveId: {
filter: {
id: /^(\/@id\/)?fresh-route-css::/,
},
handler(id) {
let name = id.startsWith("/@id/")
? id.slice("/@id/fresh-route-css::".length)
: id.slice("fresh-route-css::".length);
const idx = name.indexOf(".module.");
if (idx > -1) {
name = name.slice(0, idx);
}
return `\0fresh-route-css::${name}`;
},
},
load: {
filter: {
id: /^\0fresh-route-css::/,
},
handler(id) {
const name = id.slice("\0fresh-route-css::".length);
const route = routes.get(name);
if (route === undefined) return;
if (!isDev) {
return `export default ["__FRESH_CSS_PLACEHOLDER__"];`;
}
const imports = route.css.map((css) => `import "${css}";`).join("\n");
return `${imports}
export default ${JSON.stringify(route.css)}
`;
},
},
},
{
name: "fresh-route-css-build-ssr",
applyToEnvironment(env) {
return env.name === "ssr";
},
async writeBundle(_, bundle) {
const asset = bundle[".vite/manifest.json"];
if (asset.type === "asset") {
const manifest = JSON.parse(asset.source as string) as Manifest;
for (const info of Object.values(manifest)) {
if (info.name?.startsWith("_fresh-route___")) {
const filePath = path.join(serverOutDir, info.file);
const content = await Deno.readTextFile(filePath);
const replaced = content.replace(
`["__FRESH_CSS_PLACEHOLDER__"]`,
info.css
? JSON.stringify(info.css.map((css) => `/${css}`))
: "null",
);
await Deno.writeTextFile(filePath, replaced);
}
}
}
},
},
{
name: "fresh:route-resolver",
resolveId: {
filter: {
id: /^fresh-route::/,
},
handler(id) {
let name = id.slice("fresh-route::".length);
if (JS_REG.test(name)) {
name = name.slice(0, name.lastIndexOf("."));
}
return `\0fresh-route::${name}`;
},
},
load: {
filter: {
id: /^\0fresh-route::.*/,
},
handler(id) {
const name = id.slice("\0fresh-route::".length);
const route = routes.get(name);
if (route === undefined) return;
const fileUrl = path.toFileUrl(route.filePath).href;
const cssId = isDev
? `/@id/fresh-route-css::${name}.module.css`
: `fresh-route-css::${name}.module.css`;
// For some reason doing `export * from "foo"` is broken
// in vite.
const code = `import * as mod from "${fileUrl}";
import routeCss from "${cssId}";
export const css = routeCss;
export const config = mod.config;
export const handler = mod.handler;
export const handlers = mod.handlers;
export default mod.default;
`;
return { code };
},
},
},
];
} }
function walkUp( function walkUp(
+8 -1
View File
@@ -328,7 +328,7 @@ Deno.test({
}); });
Deno.test({ Deno.test({
name: "vite build - island css modules", name: "vite build - css modules",
fn: async () => { fn: async () => {
await launchProd( await launchProd(
{ cwd: viteResult.tmp }, { cwd: viteResult.tmp },
@@ -355,6 +355,13 @@ Deno.test({
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
.evaluate((el) => window.getComputedStyle(el as any).color); .evaluate((el) => window.getComputedStyle(el as any).color);
expect(color).toEqual("rgb(0, 0, 255)"); expect(color).toEqual("rgb(0, 0, 255)");
// Route css
color = await page
.locator(".route > h1")
// deno-lint-ignore no-explicit-any
.evaluate((el) => window.getComputedStyle(el as any).color);
expect(color).toEqual("rgb(255, 218, 185)");
}); });
}, },
); );
+16 -2
View File
@@ -1,6 +1,10 @@
import * as path from "@std/path"; import * as path from "@std/path";
import { expect } from "@std/expect"; import { expect } from "@std/expect";
import { waitForText, withBrowser } from "../../fresh/tests/test_utils.tsx"; import {
waitFor,
waitForText,
withBrowser,
} from "../../fresh/tests/test_utils.tsx";
import { import {
DEMO_DIR, DEMO_DIR,
FIXTURE_DIR, FIXTURE_DIR,
@@ -262,13 +266,14 @@ Deno.test({
}); });
Deno.test({ Deno.test({
name: "vite dev - island css modules", name: "vite dev - css modules",
fn: async () => { fn: async () => {
await withBrowser(async (page) => { await withBrowser(async (page) => {
await page.goto(`${demoServer.address()}/tests/css_modules`, { await page.goto(`${demoServer.address()}/tests/css_modules`, {
waitUntil: "networkidle2", waitUntil: "networkidle2",
}); });
await waitFor(async () => {
let color = await page let color = await page
.locator(".red > h1") .locator(".red > h1")
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
@@ -286,6 +291,15 @@ Deno.test({
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
.evaluate((el) => window.getComputedStyle(el as any).color); .evaluate((el) => window.getComputedStyle(el as any).color);
expect(color).toEqual("rgb(0, 0, 255)"); expect(color).toEqual("rgb(0, 0, 255)");
// Route css
color = await page
.locator(".route > h1")
// deno-lint-ignore no-explicit-any
.evaluate((el) => window.getComputedStyle(el as any).color);
expect(color).toEqual("rgb(255, 218, 185)");
return true;
});
}); });
}, },
sanitizeResources: false, sanitizeResources: false,