fix(vite): support ssr css modules (#3355)
Fixes https://github.com/denoland/fresh/issues/3325
This commit is contained in:
@@ -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<State>(
|
||||
def = await route();
|
||||
}
|
||||
|
||||
if (def.css !== undefined) {
|
||||
setAdditionalStyles(ctx, def.css);
|
||||
}
|
||||
|
||||
return renderRoute(ctx, def);
|
||||
});
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ export type FreshContext<State = unknown> = Context<State>;
|
||||
|
||||
export let getBuildCache: <T>(ctx: Context<T>) => BuildCache<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.
|
||||
@@ -116,6 +117,7 @@ export class Context<State> {
|
||||
next: () => Promise<Response>;
|
||||
|
||||
#buildCache: BuildCache<State>;
|
||||
#additionalStyles: string[] | null = null;
|
||||
|
||||
Component!: FunctionComponent;
|
||||
|
||||
@@ -123,6 +125,8 @@ export class Context<State> {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
getInternals = <T>(ctx: Context<T>) => ctx.#internal as any;
|
||||
getBuildCache = <T>(ctx: Context<T>) => ctx.#buildCache;
|
||||
setAdditionalStyles = <T>(ctx: Context<T>, css: string[]) =>
|
||||
ctx.#additionalStyles = css;
|
||||
}
|
||||
|
||||
constructor(
|
||||
@@ -280,6 +284,13 @@ export class Context<State> {
|
||||
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);
|
||||
|
||||
|
||||
@@ -91,6 +91,7 @@ export async function crawlRouteDir<State>(
|
||||
pattern,
|
||||
routePattern,
|
||||
lazy,
|
||||
css: [],
|
||||
overrideConfig,
|
||||
});
|
||||
}, ignore);
|
||||
|
||||
@@ -25,6 +25,7 @@ export interface FreshFsMod<State> {
|
||||
default?:
|
||||
| AnyComponent<PageProps<unknown, State>>
|
||||
| AsyncAnyComponent<PageProps<unknown, State>>;
|
||||
css?: string[];
|
||||
}
|
||||
|
||||
export interface FsRouteFile<State> {
|
||||
@@ -35,6 +36,7 @@ export interface FsRouteFile<State> {
|
||||
type: CommandType;
|
||||
routePattern: string;
|
||||
overrideConfig: RouteConfig | undefined;
|
||||
css: string[];
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -334,5 +336,6 @@ function normalizeRoute<State>(
|
||||
// deno-lint-ignore no-explicit-any
|
||||
handler: (handlers as any) ?? undefined,
|
||||
component: mod.default,
|
||||
css: rawMod.css,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -56,6 +56,8 @@ export interface Route<State> {
|
||||
component?: RouteComponent<State>;
|
||||
config?: RouteConfig;
|
||||
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";
|
||||
// @ts-ignore upstream issue https://github.com/denoland/deno/issues/30560
|
||||
import styles from "./CssRoute.module.css";
|
||||
|
||||
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 {
|
||||
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<string, { name: string; chunk: string | null }>();
|
||||
const islandsByFile = new Set<string>();
|
||||
const islandSpecByName = new Map<string, string>();
|
||||
const routeNamer = new UniqueNamer();
|
||||
const routeFileToName = new Map<string, string>();
|
||||
|
||||
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<string, FsRouteFileNoMod<any>> = 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<EnvironmentModuleNode>();
|
||||
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<EnvironmentModuleNode>();
|
||||
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<string, string>();
|
||||
|
||||
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<string, string>();
|
||||
|
||||
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(
|
||||
|
||||
@@ -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)");
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user