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 { 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);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|
||||||
|
|||||||
@@ -91,6 +91,7 @@ export async function crawlRouteDir<State>(
|
|||||||
pattern,
|
pattern,
|
||||||
routePattern,
|
routePattern,
|
||||||
lazy,
|
lazy,
|
||||||
|
css: [],
|
||||||
overrideConfig,
|
overrideConfig,
|
||||||
});
|
});
|
||||||
}, ignore);
|
}, ignore);
|
||||||
|
|||||||
@@ -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,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,307 +30,489 @@ 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
|
||||||
name: "fresh:server-snapshot",
|
const routes: Map<string, FsRouteFileNoMod<any>> = new Map();
|
||||||
applyToEnvironment(env) {
|
|
||||||
return env.name === "ssr";
|
|
||||||
},
|
|
||||||
config(_, env) {
|
|
||||||
isDev = env.command === "serve";
|
|
||||||
},
|
|
||||||
configResolved(config) {
|
|
||||||
root = config.root;
|
|
||||||
|
|
||||||
publicDir = pathWithRoot(config.publicDir, config.root);
|
return [
|
||||||
clientOutDir = pathWithRoot(
|
{
|
||||||
config.environments.client.build.outDir,
|
name: "fresh:server-snapshot",
|
||||||
config.root,
|
applyToEnvironment(env) {
|
||||||
);
|
return env.name === "ssr";
|
||||||
|
|
||||||
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/,
|
|
||||||
},
|
},
|
||||||
handler(id) {
|
config(_, env) {
|
||||||
if (id === modName) {
|
isDev = env.command === "serve";
|
||||||
return `\0${modName}`;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
load: {
|
|
||||||
filter: {
|
|
||||||
id: /\0fresh:server-snapshot/,
|
|
||||||
},
|
},
|
||||||
|
configResolved(config) {
|
||||||
|
root = config.root;
|
||||||
|
|
||||||
async handler() {
|
publicDir = pathWithRoot(config.publicDir, config.root);
|
||||||
const result = await crawlFsItem({
|
clientOutDir = pathWithRoot(
|
||||||
islandDir: options.islandsDir,
|
config.environments.client.build.outDir,
|
||||||
routeDir: options.routeDir,
|
config.root,
|
||||||
ignore: options.ignore,
|
);
|
||||||
});
|
serverOutDir = pathWithRoot(
|
||||||
|
config.environments.ssr.build.outDir,
|
||||||
for (let i = 0; i < result.islands.length; i++) {
|
config.root,
|
||||||
const spec = result.islands[i];
|
);
|
||||||
const specName = specToName(spec);
|
|
||||||
const name = options.namer.getUniqueName(specName);
|
|
||||||
|
|
||||||
|
options.islandSpecifiers.forEach((name, spec) => {
|
||||||
islands.set(spec, { name, chunk: null });
|
islands.set(spec, { name, chunk: null });
|
||||||
islandSpecByName.set(name, spec);
|
islandSpecByName.set(name, spec);
|
||||||
islandsByFile.add(spec);
|
// islandsByFile.add(spec);
|
||||||
}
|
});
|
||||||
|
},
|
||||||
|
configureServer(viteServer) {
|
||||||
|
server = viteServer;
|
||||||
|
|
||||||
const staticFiles: PendingStaticFile[] = [];
|
viteServer.watcher.on("all", (ev, filePath) => {
|
||||||
let islandMods: IslandModChunk[] = [];
|
const { client, ssr } = viteServer.environments;
|
||||||
let clientEntry = "/@id/fresh:client-entry";
|
|
||||||
let buildId = "";
|
|
||||||
const entryAssets: string[] = [];
|
|
||||||
|
|
||||||
if (isDev && server !== undefined) {
|
// We can't just check if it's in the client module graph
|
||||||
for (const id of islands.keys()) {
|
// because plugins like tailwindcss import _everything_.
|
||||||
const mod = server.environments.client.moduleGraph.getModuleById(
|
// Instead, we walk up the module graph to see if the file
|
||||||
id,
|
// is imported by an island or the client entry file.
|
||||||
);
|
const mods = client.moduleGraph.getModulesByFile(filePath);
|
||||||
if (mod !== undefined) {
|
if (mods !== undefined) {
|
||||||
const def = islands.get(id);
|
const seen = new Set<EnvironmentModuleNode>();
|
||||||
if (def !== undefined) def.chunk = mod.url;
|
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]) => {
|
// Check for route files. We need to invalidate the snapshot if
|
||||||
return {
|
// they are removed or added.
|
||||||
name: def.name,
|
if (
|
||||||
server: id,
|
(ev === "add" || ev === "unlink") &&
|
||||||
browser: def.chunk ?? `/@id/fresh-island::${def.name}`,
|
!/[\\/]+\(_[^)]+\)[\\/]+/.test(filePath)
|
||||||
css: [],
|
) {
|
||||||
};
|
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()) {
|
for (let i = 0; i < result.islands.length; i++) {
|
||||||
const resolved = await this.resolve(spec);
|
const spec = result.islands[i];
|
||||||
|
const specName = specToName(spec);
|
||||||
|
const name = options.namer.getUniqueName(specName);
|
||||||
|
|
||||||
if (resolved === null) continue;
|
islands.set(spec, { name, chunk: null });
|
||||||
|
islandSpecByName.set(name, spec);
|
||||||
const id = resolved.id.startsWith("\0")
|
islandsByFile.add(spec);
|
||||||
? resolved.id.slice(1)
|
|
||||||
: resolved.id;
|
|
||||||
|
|
||||||
resolvedIslandSpecs.set(id, 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)) {
|
routeFileToName.set(route.filePath, name);
|
||||||
if (chunk.name === clientEntryName) {
|
routes.set(name, route);
|
||||||
clientEntry = pathToSpec(clientOutDir, chunk.file);
|
}
|
||||||
|
|
||||||
|
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({
|
islandMods = Array.from(islands.entries()).map(([id, def]) => {
|
||||||
filePath: path.join(clientOutDir, chunk.file),
|
return {
|
||||||
pathname: chunk.file,
|
name: def.name,
|
||||||
hash: null,
|
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 (const spec of options.islandSpecifiers.keys()) {
|
||||||
for (let i = 0; i < chunk.css.length; i++) {
|
const resolved = await this.resolve(spec);
|
||||||
const id = chunk.css[i];
|
|
||||||
|
|
||||||
const pathname = `/${id}`;
|
if (resolved === null) continue;
|
||||||
|
|
||||||
staticFiles.push({
|
const id = resolved.id.startsWith("\0")
|
||||||
filePath: path.join(clientOutDir, id),
|
? resolved.id.slice(1)
|
||||||
hash: null,
|
: resolved.id;
|
||||||
pathname,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (chunk.name === clientEntryName) {
|
resolvedIslandSpecs.set(id, spec);
|
||||||
entryAssets.push(pathname);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const namer = new UniqueNamer();
|
const clientEntryName = "client-entry";
|
||||||
if (chunk.name === "client-snapshot") {
|
|
||||||
for (const id of chunk.dynamicImports ?? []) {
|
|
||||||
const mod = manifest[id];
|
|
||||||
|
|
||||||
let serverPath = path.join(root, mod.src ?? id);
|
for (const chunk of Object.values(manifest)) {
|
||||||
const idx = mod.src?.indexOf("deno::") ?? -1;
|
if (chunk.name === clientEntryName) {
|
||||||
|
clientEntry = pathToSpec(clientOutDir, chunk.file);
|
||||||
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({
|
staticFiles.push({
|
||||||
filePath,
|
filePath: path.join(clientOutDir, chunk.file),
|
||||||
|
pathname: chunk.file,
|
||||||
hash: null,
|
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",
|
name: "fresh:route-resolver",
|
||||||
resolveId: {
|
resolveId: {
|
||||||
filter: {
|
filter: {
|
||||||
id: /^fresh-island::.*/,
|
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) {
|
load: {
|
||||||
let name = id.slice("fresh-island::".length);
|
filter: {
|
||||||
|
id: /^\0fresh-route::.*/,
|
||||||
|
},
|
||||||
|
handler(id) {
|
||||||
|
const name = id.slice("\0fresh-route::".length);
|
||||||
|
|
||||||
if (JS_REG.test(name)) {
|
const route = routes.get(name);
|
||||||
name = name.slice(0, name.lastIndexOf("."));
|
if (route === undefined) return;
|
||||||
}
|
|
||||||
|
|
||||||
const spec = islandSpecByName.get(name);
|
const fileUrl = path.toFileUrl(route.filePath).href;
|
||||||
if (spec !== undefined) return spec;
|
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(
|
||||||
|
|||||||
@@ -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)");
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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,30 +266,40 @@ 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",
|
||||||
});
|
});
|
||||||
|
|
||||||
let color = await page
|
await waitFor(async () => {
|
||||||
.locator(".red > h1")
|
let color = await page
|
||||||
// deno-lint-ignore no-explicit-any
|
.locator(".red > h1")
|
||||||
.evaluate((el) => window.getComputedStyle(el as any).color);
|
// deno-lint-ignore no-explicit-any
|
||||||
expect(color).toEqual("rgb(255, 0, 0)");
|
.evaluate((el) => window.getComputedStyle(el as any).color);
|
||||||
|
expect(color).toEqual("rgb(255, 0, 0)");
|
||||||
|
|
||||||
color = await page
|
color = await page
|
||||||
.locator(".green > h1")
|
.locator(".green > h1")
|
||||||
// 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, 128, 0)");
|
expect(color).toEqual("rgb(0, 128, 0)");
|
||||||
|
|
||||||
color = await page
|
color = await page
|
||||||
.locator(".blue > h1")
|
.locator(".blue > h1")
|
||||||
// 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,
|
||||||
|
|||||||
Reference in New Issue
Block a user