diff --git a/packages/fresh/src/commands.ts b/packages/fresh/src/commands.ts index da125050..b6979f58 100644 --- a/packages/fresh/src/commands.ts +++ b/packages/fresh/src/commands.ts @@ -1,3 +1,4 @@ +import { setAdditionalStyles } from "./context.ts"; import { HttpError } from "./error.ts"; import { isHandlerByMethod, type PageResponse } from "./handlers.ts"; import type { MaybeLazyMiddleware, Middleware } from "./middlewares/mod.ts"; @@ -282,6 +283,10 @@ function applyCommandsInner( def = await route(); } + if (def.css !== undefined) { + setAdditionalStyles(ctx, def.css); + } + return renderRoute(ctx, def); }); diff --git a/packages/fresh/src/context.ts b/packages/fresh/src/context.ts index 3f0d4353..c3bb152a 100644 --- a/packages/fresh/src/context.ts +++ b/packages/fresh/src/context.ts @@ -52,6 +52,7 @@ export type FreshContext = Context; export let getBuildCache: (ctx: Context) => BuildCache; export let getInternals: (ctx: Context) => UiTree; +export let setAdditionalStyles: (ctx: Context, css: string[]) => void; /** * The context passed to every middleware. It is unique for every request. @@ -116,6 +117,7 @@ export class Context { next: () => Promise; #buildCache: BuildCache; + #additionalStyles: string[] | null = null; Component!: FunctionComponent; @@ -123,6 +125,8 @@ export class Context { // deno-lint-ignore no-explicit-any getInternals = (ctx: Context) => ctx.#internal as any; getBuildCache = (ctx: Context) => ctx.#buildCache; + setAdditionalStyles = (ctx: Context, css: string[]) => + ctx.#additionalStyles = css; } constructor( @@ -280,6 +284,13 @@ export class Context { partialId, ); + if (this.#additionalStyles !== null) { + for (let i = 0; i < this.#additionalStyles.length; i++) { + const css = this.#additionalStyles[i]; + state.islandAssets.add(css); + } + } + try { setRenderState(state); diff --git a/packages/fresh/src/dev/fs_crawl.ts b/packages/fresh/src/dev/fs_crawl.ts index 126358af..cc61f666 100644 --- a/packages/fresh/src/dev/fs_crawl.ts +++ b/packages/fresh/src/dev/fs_crawl.ts @@ -91,6 +91,7 @@ export async function crawlRouteDir( pattern, routePattern, lazy, + css: [], overrideConfig, }); }, ignore); diff --git a/packages/fresh/src/fs_routes.ts b/packages/fresh/src/fs_routes.ts index d32abc2f..0203910b 100644 --- a/packages/fresh/src/fs_routes.ts +++ b/packages/fresh/src/fs_routes.ts @@ -25,6 +25,7 @@ export interface FreshFsMod { default?: | AnyComponent> | AsyncAnyComponent>; + css?: string[]; } export interface FsRouteFile { @@ -35,6 +36,7 @@ export interface FsRouteFile { type: CommandType; routePattern: string; overrideConfig: RouteConfig | undefined; + css: string[]; } // deno-lint-ignore no-explicit-any @@ -334,5 +336,6 @@ function normalizeRoute( // deno-lint-ignore no-explicit-any handler: (handlers as any) ?? undefined, component: mod.default, + css: rawMod.css, }; } diff --git a/packages/fresh/src/types.ts b/packages/fresh/src/types.ts index a9d229e4..e3a4d0ba 100644 --- a/packages/fresh/src/types.ts +++ b/packages/fresh/src/types.ts @@ -56,6 +56,8 @@ export interface Route { component?: RouteComponent; config?: RouteConfig; handler?: RouteHandler; + /** Additional .css files to load */ + css?: string[]; } /** diff --git a/packages/plugin-vite/demo/routes/tests/CssRoute.module.css b/packages/plugin-vite/demo/routes/tests/CssRoute.module.css new file mode 100644 index 00000000..27121e17 --- /dev/null +++ b/packages/plugin-vite/demo/routes/tests/CssRoute.module.css @@ -0,0 +1,3 @@ +.root { + color: peachpuff; +} diff --git a/packages/plugin-vite/demo/routes/tests/css_modules.tsx b/packages/plugin-vite/demo/routes/tests/css_modules.tsx index 93d24944..e1452967 100644 --- a/packages/plugin-vite/demo/routes/tests/css_modules.tsx +++ b/packages/plugin-vite/demo/routes/tests/css_modules.tsx @@ -1,5 +1,14 @@ 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() { - return ; + return ( +
+ +
+

peachpuff text

+
+
+ ); } diff --git a/packages/plugin-vite/src/plugins/server_entry.ts b/packages/plugin-vite/src/plugins/server_entry.ts index 8022c531..1943968a 100644 --- a/packages/plugin-vite/src/plugins/server_entry.ts +++ b/packages/plugin-vite/src/plugins/server_entry.ts @@ -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}`, + }); + } + } } } diff --git a/packages/plugin-vite/src/plugins/server_snapshot.ts b/packages/plugin-vite/src/plugins/server_snapshot.ts index 07c1ea9f..298fc26f 100644 --- a/packages/plugin-vite/src/plugins/server_snapshot.ts +++ b/packages/plugin-vite/src/plugins/server_snapshot.ts @@ -7,6 +7,7 @@ import type { import { crawlFsItem, fsAdapter, + type FsRouteFileNoMod, generateSnapshotServer, type IslandModChunk, pathToSpec, @@ -29,307 +30,489 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] { let server: ViteDevServer | undefined; let clientOutDir = ""; + let serverOutDir = ""; let root = ""; let publicDir = ""; const islands = new Map(); const islandsByFile = new Set(); const islandSpecByName = new Map(); + const routeNamer = new UniqueNamer(); + const routeFileToName = new Map(); - return [{ - name: "fresh:server-snapshot", - applyToEnvironment(env) { - return env.name === "ssr"; - }, - config(_, env) { - isDev = env.command === "serve"; - }, - configResolved(config) { - root = config.root; + // deno-lint-ignore no-explicit-any + const routes: Map> = new Map(); - publicDir = pathWithRoot(config.publicDir, config.root); - clientOutDir = pathWithRoot( - config.environments.client.build.outDir, - config.root, - ); - - options.islandSpecifiers.forEach((name, spec) => { - islands.set(spec, { name, chunk: null }); - islandSpecByName.set(name, spec); - // islandsByFile.add(spec); - }); - }, - configureServer(viteServer) { - server = viteServer; - - viteServer.watcher.on("all", (ev, filePath) => { - const { client, ssr } = viteServer.environments; - - // We can't just check if it's in the client module graph - // because plugins like tailwindcss import _everything_. - // Instead, we walk up the module graph to see if the file - // is imported by an island or the client entry file. - const mods = client.moduleGraph.getModulesByFile(filePath); - if (mods !== undefined) { - const seen = new Set(); - const maybe = Array.from(mods); - for (let i = 0; i < maybe.length; i++) { - const mod = maybe[i]; - - const isIslandFile = walkUp( - mod, - (m) => m.file !== null && islandsByFile.has(m.file), - seen, - ); - - // No need to notify manually, vite takes care of this. - if (isIslandFile) return; - } - } - - // Check for route files. We need to invalidate the snapshot if - // they are removed or added. - if ( - (ev === "add" || ev === "unlink") && - !/[\\/]+\(_[^)]+\)[\\/]+/.test(filePath) - ) { - const relRoutes = path.relative(options.routeDir, filePath); - if (!relRoutes.startsWith("..")) { - const mod = ssr.moduleGraph.getModuleById(`\0${modName}`); - if (mod !== undefined) { - // Clear state - islands.clear(); - islandsByFile.clear(); - islandSpecByName.clear(); - - ssr.moduleGraph.invalidateModule(mod); - } - } - } - - // Finally, notify the client - viteServer.ws.send("fresh:reload"); - }); - }, - resolveId: { - filter: { - id: /fresh:server-snapshot/, + return [ + { + name: "fresh:server-snapshot", + applyToEnvironment(env) { + return env.name === "ssr"; }, - handler(id) { - if (id === modName) { - return `\0${modName}`; - } - }, - }, - load: { - filter: { - id: /\0fresh:server-snapshot/, + config(_, env) { + isDev = env.command === "serve"; }, + configResolved(config) { + root = config.root; - async handler() { - const result = await crawlFsItem({ - islandDir: options.islandsDir, - routeDir: options.routeDir, - ignore: options.ignore, - }); - - for (let i = 0; i < result.islands.length; i++) { - const spec = result.islands[i]; - const specName = specToName(spec); - const name = options.namer.getUniqueName(specName); + publicDir = pathWithRoot(config.publicDir, config.root); + clientOutDir = pathWithRoot( + config.environments.client.build.outDir, + config.root, + ); + serverOutDir = pathWithRoot( + config.environments.ssr.build.outDir, + config.root, + ); + options.islandSpecifiers.forEach((name, spec) => { islands.set(spec, { name, chunk: null }); islandSpecByName.set(name, spec); - islandsByFile.add(spec); - } + // islandsByFile.add(spec); + }); + }, + configureServer(viteServer) { + server = viteServer; - const staticFiles: PendingStaticFile[] = []; - let islandMods: IslandModChunk[] = []; - let clientEntry = "/@id/fresh:client-entry"; - let buildId = ""; - const entryAssets: string[] = []; + viteServer.watcher.on("all", (ev, filePath) => { + const { client, ssr } = viteServer.environments; - if (isDev && server !== undefined) { - for (const id of islands.keys()) { - const mod = server.environments.client.moduleGraph.getModuleById( - id, - ); - if (mod !== undefined) { - const def = islands.get(id); - if (def !== undefined) def.chunk = mod.url; + // We can't just check if it's in the client module graph + // because plugins like tailwindcss import _everything_. + // Instead, we walk up the module graph to see if the file + // is imported by an island or the client entry file. + const mods = client.moduleGraph.getModulesByFile(filePath); + if (mods !== undefined) { + const seen = new Set(); + const maybe = Array.from(mods); + for (let i = 0; i < maybe.length; i++) { + const mod = maybe[i]; + + const isIslandFile = walkUp( + mod, + (m) => m.file !== null && islandsByFile.has(m.file), + seen, + ); + + // No need to notify manually, vite takes care of this. + if (isIslandFile) return; } } - islandMods = Array.from(islands.entries()).map(([id, def]) => { - return { - name: def.name, - server: id, - browser: def.chunk ?? `/@id/fresh-island::${def.name}`, - css: [], - }; + // Check for route files. We need to invalidate the snapshot if + // they are removed or added. + if ( + (ev === "add" || ev === "unlink") && + !/[\\/]+\(_[^)]+\)[\\/]+/.test(filePath) + ) { + const relRoutes = path.relative(options.routeDir, filePath); + if (!relRoutes.startsWith("..")) { + const mod = ssr.moduleGraph.getModuleById(`\0${modName}`); + if (mod !== undefined) { + // Clear state + islands.clear(); + islandsByFile.clear(); + islandSpecByName.clear(); + + ssr.moduleGraph.invalidateModule(mod); + } + } + } + + // Finally, notify the client + viteServer.ws.send("fresh:reload"); + }); + }, + resolveId: { + filter: { + id: /fresh:server-snapshot/, + }, + handler(id) { + if (id === modName) { + return `\0${modName}`; + } + }, + }, + load: { + filter: { + id: /\0fresh:server-snapshot/, + }, + + async handler() { + const result = await crawlFsItem({ + islandDir: options.islandsDir, + routeDir: options.routeDir, + ignore: options.ignore, }); - } else { - buildId = await getBuildId(false); - const manifest = JSON.parse( - await Deno.readTextFile( - path.join(clientOutDir, ".vite", "manifest.json"), - ), - ) as Manifest; - const resolvedIslandSpecs = new Map(); - for (const spec of options.islandSpecifiers.keys()) { - const resolved = await this.resolve(spec); + for (let i = 0; i < result.islands.length; i++) { + const spec = result.islands[i]; + const specName = specToName(spec); + const name = options.namer.getUniqueName(specName); - if (resolved === null) continue; - - const id = resolved.id.startsWith("\0") - ? resolved.id.slice(1) - : resolved.id; - - resolvedIslandSpecs.set(id, spec); + islands.set(spec, { name, chunk: null }); + islandSpecByName.set(name, spec); + islandsByFile.add(spec); } - const clientEntryName = "client-entry"; + for (let i = 0; i < result.routes.length; i++) { + const route = result.routes[i]; + const name = routeNamer.getUniqueName(route.id); - for (const chunk of Object.values(manifest)) { - if (chunk.name === clientEntryName) { - clientEntry = pathToSpec(clientOutDir, chunk.file); + routeFileToName.set(route.filePath, name); + routes.set(name, route); + } + + const staticFiles: PendingStaticFile[] = []; + let islandMods: IslandModChunk[] = []; + let clientEntry = "/@id/fresh:client-entry"; + let buildId = ""; + const entryAssets: string[] = []; + + if (isDev && server !== undefined) { + for (const id of islands.keys()) { + const mod = server.environments.client.moduleGraph.getModuleById( + id, + ); + if (mod !== undefined) { + const def = islands.get(id); + if (def !== undefined) def.chunk = mod.url; + } } - staticFiles.push({ - filePath: path.join(clientOutDir, chunk.file), - pathname: chunk.file, - hash: null, + islandMods = Array.from(islands.entries()).map(([id, def]) => { + return { + name: def.name, + server: id, + browser: def.chunk ?? `/@id/fresh-island::${def.name}`, + css: [], + }; }); + } else { + buildId = await getBuildId(false); + const manifest = JSON.parse( + await Deno.readTextFile( + path.join(clientOutDir, ".vite", "manifest.json"), + ), + ) as Manifest; + const resolvedIslandSpecs = new Map(); - if (chunk.css !== undefined) { - for (let i = 0; i < chunk.css.length; i++) { - const id = chunk.css[i]; + for (const spec of options.islandSpecifiers.keys()) { + const resolved = await this.resolve(spec); - const pathname = `/${id}`; + if (resolved === null) continue; - staticFiles.push({ - filePath: path.join(clientOutDir, id), - hash: null, - pathname, - }); + const id = resolved.id.startsWith("\0") + ? resolved.id.slice(1) + : resolved.id; - if (chunk.name === clientEntryName) { - entryAssets.push(pathname); - } - } + resolvedIslandSpecs.set(id, spec); } - const namer = new UniqueNamer(); - if (chunk.name === "client-snapshot") { - for (const id of chunk.dynamicImports ?? []) { - const mod = manifest[id]; + const clientEntryName = "client-entry"; - let serverPath = path.join(root, mod.src ?? id); - const idx = mod.src?.indexOf("deno::") ?? -1; - - if (idx > -1 && mod.src) { - const src = mod.src - .slice(idx) - .replace( - /(https?):\/([^/])/, - (_m, protocol, rest) => { - return `${protocol}://${rest}`; - }, - ); - serverPath = resolvedIslandSpecs.get(src)!; - } - - let spec = pathToSpec(clientOutDir, mod.file); - - if (spec.startsWith("./")) { - spec = spec.slice(1); - } - - const chunkCss = mod.css?.map((id) => `/${id}`) ?? []; - - const name = namer.getUniqueName(specToName(id)); - islandMods.push({ - name, - browser: spec, - server: serverPath, - css: chunkCss, - }); + for (const chunk of Object.values(manifest)) { + if (chunk.name === clientEntryName) { + clientEntry = pathToSpec(clientOutDir, chunk.file); } - } - } - - if (await fsAdapter.isDirectory(publicDir)) { - const entries = await fsAdapter.walk( - publicDir, - { - followSymlinks: false, - includeDirs: false, - includeFiles: true, - skip: options.ignore, - }, - ); - - for await (const entry of entries) { - const relative = path.relative(publicDir, entry.path); - const filePath = path.join(clientOutDir, relative); - - try { - await Deno.mkdir(path.dirname(filePath), { recursive: true }); - } catch (err) { - if (!(err instanceof Deno.errors.AlreadyExists)) { - throw err; - } - } - await Deno.copyFile(entry.path, filePath); staticFiles.push({ - filePath, + filePath: path.join(clientOutDir, chunk.file), + pathname: chunk.file, hash: null, - pathname: relative, }); + + if (chunk.css !== undefined) { + for (let i = 0; i < chunk.css.length; i++) { + const id = chunk.css[i]; + + const pathname = `/${id}`; + + staticFiles.push({ + filePath: path.join(clientOutDir, id), + hash: null, + pathname, + }); + + if (chunk.name === clientEntryName) { + entryAssets.push(pathname); + } + } + } + + const namer = new UniqueNamer(); + if (chunk.name === "client-snapshot") { + for (const id of chunk.dynamicImports ?? []) { + const mod = manifest[id]; + + let serverPath = path.join(root, mod.src ?? id); + const idx = mod.src?.indexOf("deno::") ?? -1; + + if (idx > -1 && mod.src) { + const src = mod.src + .slice(idx) + .replace( + /(https?):\/([^/])/, + (_m, protocol, rest) => { + return `${protocol}://${rest}`; + }, + ); + serverPath = resolvedIslandSpecs.get(src)!; + } + + let spec = pathToSpec(clientOutDir, mod.file); + + if (spec.startsWith("./")) { + spec = spec.slice(1); + } + + const chunkCss = mod.css?.map((id) => `/${id}`) ?? []; + + const name = namer.getUniqueName(specToName(id)); + islandMods.push({ + name, + browser: spec, + server: serverPath, + css: chunkCss, + }); + } + } + } + + if (await fsAdapter.isDirectory(publicDir)) { + const entries = await fsAdapter.walk( + publicDir, + { + followSymlinks: false, + includeDirs: false, + includeFiles: true, + skip: options.ignore, + }, + ); + + for await (const entry of entries) { + const relative = path.relative(publicDir, entry.path); + const filePath = path.join(clientOutDir, relative); + + try { + await Deno.mkdir(path.dirname(filePath), { recursive: true }); + } catch (err) { + if (!(err instanceof Deno.errors.AlreadyExists)) { + throw err; + } + } + await Deno.copyFile(entry.path, filePath); + + staticFiles.push({ + filePath, + hash: null, + pathname: relative, + }); + } + } + } + + const code = await generateSnapshotServer({ + outDir: path.join(clientOutDir, ".."), + staticFiles, + buildId, + clientEntry, + entryAssets, + fsRoutesFiles: result.routes, + islands: islandMods, + writeSpecifier: (file) => { + const def = islands.get(file); + if (def) { + return `fresh-island::${def.name}`; + } + const routeDef = routeFileToName.get(file); + if (routeDef !== undefined) { + return `fresh-route::${routeDef}`; + } + return path.toFileUrl(file).href; + }, + }); + + 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", + resolveId: { + filter: { + id: /^fresh-island::.*/, + }, + handler(id) { + let name = id.slice("fresh-island::".length); + + if (JS_REG.test(name)) { + name = name.slice(0, name.lastIndexOf(".")); + } + + const spec = islandSpecByName.get(name); + 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); } } } - - const code = await generateSnapshotServer({ - outDir: path.join(clientOutDir, ".."), - staticFiles, - buildId, - clientEntry, - entryAssets, - fsRoutesFiles: result.routes, - islands: islandMods, - writeSpecifier: (file) => { - const def = islands.get(file); - if (def) { - return `fresh-island::${def.name}`; - } - return path.toFileUrl(file).href; - }, - }); - - return code; }, }, - }, { - name: "fresh:island-resolver", - resolveId: { - filter: { - id: /^fresh-island::.*/, + { + 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}`; + }, }, - handler(id) { - let name = id.slice("fresh-island::".length); + load: { + filter: { + id: /^\0fresh-route::.*/, + }, + handler(id) { + const name = id.slice("\0fresh-route::".length); - if (JS_REG.test(name)) { - name = name.slice(0, name.lastIndexOf(".")); - } + const route = routes.get(name); + if (route === undefined) return; - const spec = islandSpecByName.get(name); - if (spec !== undefined) return spec; + 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( diff --git a/packages/plugin-vite/tests/build_test.ts b/packages/plugin-vite/tests/build_test.ts index 56b28ede..d1dafc1a 100644 --- a/packages/plugin-vite/tests/build_test.ts +++ b/packages/plugin-vite/tests/build_test.ts @@ -328,7 +328,7 @@ Deno.test({ }); Deno.test({ - name: "vite build - island css modules", + name: "vite build - css modules", fn: async () => { await launchProd( { cwd: viteResult.tmp }, @@ -355,6 +355,13 @@ Deno.test({ // deno-lint-ignore no-explicit-any .evaluate((el) => window.getComputedStyle(el as any).color); 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)"); }); }, ); diff --git a/packages/plugin-vite/tests/dev_server_test.ts b/packages/plugin-vite/tests/dev_server_test.ts index 361cb525..1a0f5ede 100644 --- a/packages/plugin-vite/tests/dev_server_test.ts +++ b/packages/plugin-vite/tests/dev_server_test.ts @@ -1,6 +1,10 @@ import * as path from "@std/path"; 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 { DEMO_DIR, FIXTURE_DIR, @@ -262,30 +266,40 @@ Deno.test({ }); Deno.test({ - name: "vite dev - island css modules", + name: "vite dev - css modules", fn: async () => { await withBrowser(async (page) => { await page.goto(`${demoServer.address()}/tests/css_modules`, { waitUntil: "networkidle2", }); - let color = await page - .locator(".red > h1") - // deno-lint-ignore no-explicit-any - .evaluate((el) => window.getComputedStyle(el as any).color); - expect(color).toEqual("rgb(255, 0, 0)"); + await waitFor(async () => { + let color = await page + .locator(".red > h1") + // deno-lint-ignore no-explicit-any + .evaluate((el) => window.getComputedStyle(el as any).color); + expect(color).toEqual("rgb(255, 0, 0)"); - color = await page - .locator(".green > h1") - // deno-lint-ignore no-explicit-any - .evaluate((el) => window.getComputedStyle(el as any).color); - expect(color).toEqual("rgb(0, 128, 0)"); + color = await page + .locator(".green > h1") + // deno-lint-ignore no-explicit-any + .evaluate((el) => window.getComputedStyle(el as any).color); + expect(color).toEqual("rgb(0, 128, 0)"); - color = await page - .locator(".blue > h1") - // deno-lint-ignore no-explicit-any - .evaluate((el) => window.getComputedStyle(el as any).color); - expect(color).toEqual("rgb(0, 0, 255)"); + color = await page + .locator(".blue > h1") + // deno-lint-ignore no-explicit-any + .evaluate((el) => window.getComputedStyle(el as any).color); + 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,