fix(vite): asset handling (#3225)

This PR reworks asset handling in our vite plugin. Importing assets in
js is now supported.
This commit is contained in:
Marvin Hagemeister
2025-08-19 16:45:33 +02:00
committed by GitHub
parent 54110c6372
commit afdf5eaf6c
47 changed files with 760 additions and 85 deletions
+6
View File
@@ -19,6 +19,7 @@ export interface BuildSnapshot<State> {
fsRoutes: FsRouteFile<State>[];
staticFiles: Map<string, FileSnapshot>;
islands: ServerIslandRegistry;
entryAssets: string[];
}
export interface StaticFile {
@@ -39,6 +40,7 @@ export interface BuildCache<State = any> {
};
getFsRoutes(): Command<State>[];
readFile(pathname: string): Promise<StaticFile | null>;
getEntryAssets(): string[];
}
export class ProdBuildCache<State> implements BuildCache<State> {
@@ -54,6 +56,10 @@ export class ProdBuildCache<State> implements BuildCache<State> {
this.clientEntry = snapshot.clientEntry;
}
getEntryAssets(): string[] {
return this.#snapshot.entryAssets;
}
getFsRoutes(): Command<State>[] {
return fsItemsToCommands(this.#snapshot.fsRoutes);
}
+2
View File
@@ -8,3 +8,5 @@ export const MINUTE = SECOND * 60;
export const HOUR = MINUTE * 60;
export const DAY = HOUR * 24;
export const WEEK = DAY * 7;
export const ASSET_CACHE_BUST_KEY = "__frsh_c";
+36 -12
View File
@@ -81,6 +81,10 @@ export class MemoryBuildCache<State> implements DevBuildCache<State> {
this.clientEntry = getClientEntry(config.buildId);
}
getEntryAssets(): string[] {
return [];
}
getFsRoutes(): Command<State>[] {
return this.#commands;
}
@@ -247,6 +251,10 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
this.root = config.root;
}
getEntryAssets(): string[] {
return [];
}
getFsRoutes(): Command<State>[] {
return [];
}
@@ -357,6 +365,7 @@ export class DiskBuildCache<State> implements DevBuildCache<State> {
},
fsRoutesFiles: this.#fsRoutes.files,
outDir: root,
entryAssets: [],
}),
);
@@ -422,6 +431,7 @@ export async function generateSnapshotServer(
// deno-lint-ignore no-explicit-any
fsRoutesFiles: FsRouteFileNoMod<any>[];
staticFiles: PendingStaticFile[];
entryAssets: string[];
writeSpecifier: (filePath: string) => string;
},
): Promise<string> {
@@ -475,21 +485,13 @@ export async function generateSnapshotServer(
const staticFiles = await Promise.all(
options.staticFiles.map(async (item) => {
const file = await Deno.open(item.filePath);
const hash = item.hash ? item.hash : await hashContent(file.readable);
const url = new URL(item.pathname, "http://localhost");
return {
name: url.pathname,
hash,
filePath: path.isAbsolute(item.filePath)
? path.relative(outDir, item.filePath)
: item.filePath,
contentType: getContentType(item.filePath),
};
return await prepareStaticFile(item, outDir);
}),
);
const entryAssets = options.entryAssets.map((url) => JSON.stringify(url))
.join(",\n");
return `${EDIT_WARNING}
import { IslandPreparer } from "fresh/internal";
${islandImports}
@@ -510,12 +512,34 @@ ${
}
]);
export const entryAssets = [${entryAssets}];
export const fsRoutes = [
${serializedFsRoutes}
];
`.replaceAll(/\n[\n]+/g, "\n\n");
}
export async function prepareStaticFile(
item: PendingStaticFile,
outDir: string,
): Promise<
{ name: string; hash: string; filePath: string; contentType: string }
> {
const file = await Deno.open(item.filePath);
const hash = item.hash ? item.hash : await hashContent(file.readable);
const url = new URL(item.pathname, "http://localhost");
return {
name: url.pathname,
hash,
filePath: path.isAbsolute(item.filePath)
? path.relative(outDir, item.filePath)
: item.filePath,
contentType: getContentType(item.filePath),
};
}
export function generateServerEntry(
options: {
root: string;
+1
View File
@@ -3,3 +3,4 @@ import * as path from "@std/path";
export { setBuildCache } from "./app.ts";
export { IslandPreparer, ProdBuildCache } from "./build_cache.ts";
export { path };
export { ASSET_CACHE_BUST_KEY } from "./constants.ts";
+1
View File
@@ -6,6 +6,7 @@ export {
generateSnapshotServer,
type IslandModChunk,
type PendingStaticFile,
prepareStaticFile,
} from "./dev/dev_build_cache.ts";
export { specToName } from "./dev/builder.ts";
export { pathToSpec, UniqueNamer } from "./utils.ts";
@@ -1,5 +1,5 @@
import type { Middleware } from "./mod.ts";
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
import { ASSET_CACHE_BUST_KEY } from "../constants.ts";
import { BUILD_ID } from "@fresh/build-id";
import { tracer } from "../otel.ts";
import { getBuildCache } from "../context.ts";
@@ -2,7 +2,7 @@ import { staticFiles } from "./static_files.ts";
import { serveMiddleware } from "../test_utils.ts";
import type { BuildCache, StaticFile } from "../build_cache.ts";
import { expect } from "@std/expect";
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
import { ASSET_CACHE_BUST_KEY } from "../constants.ts";
import { BUILD_ID } from "@fresh/build-id";
import type { Command } from "../commands.ts";
import type { ServerIslandRegistry } from "../context.ts";
@@ -32,6 +32,10 @@ class MockBuildCache implements BuildCache {
}
}
getEntryAssets(): string[] {
return [];
}
// deno-lint-ignore no-explicit-any
getFsRoutes(): Command<any>[] {
return [];
+13 -1
View File
@@ -14,6 +14,7 @@ import type { Context } from "./context.ts";
import { recordSpanError, tracer } from "./otel.ts";
import { DEV_ERROR_OVERLAY_URL } from "./constants.ts";
import { renderToString } from "preact-render-to-string";
import { escape as escapeHtml } from "@std/html";
export type AsyncAnyComponent<P> = {
(
@@ -74,7 +75,18 @@ export function preactRender<State, Data>(
res = `<body>${res}${scripts}</body>`;
}
if (!state.renderedHtmlHead) {
res = `<head><meta charset="utf-8"></head>${res}`;
let head = `<head><meta charset="utf-8">`;
const entryAssets = state.buildCache.getEntryAssets();
for (let i = 0; i < entryAssets.length; i++) {
const asset = entryAssets[i];
if (asset.endsWith(".css")) {
head += `<link rel="stylesheet" href="${escapeHtml(asset)}">`;
}
}
res = `${head}</head>${res}`;
}
if (!state.renderedHtmlTag) {
res = `<html>${res}</html>`;
@@ -12,7 +12,7 @@ import {
import type { ReadonlySignal, Signal } from "@preact/signals";
import type { Stringifiers } from "../../jsonify/stringify.ts";
import type { PageProps } from "../../render.ts";
import { Partial, type PartialProps } from "../shared.ts";
import { asset, Partial, type PartialProps } from "../shared.ts";
import { stringify } from "../../jsonify/stringify.ts";
import type { Island } from "../../context.ts";
import {
@@ -255,9 +255,39 @@ options[OptionsType.DIFF] = (vnode) => {
case "html":
RENDER_STATE!.renderedHtmlTag = true;
break;
case "head":
case "head": {
RENDER_STATE!.renderedHtmlHead = true;
const entryAssets = RENDER_STATE.buildCache.getEntryAssets();
if (entryAssets.length > 0) {
const items: VNode[] = [];
for (let i = 0; i < entryAssets.length; i++) {
const id = entryAssets[i];
if (id.endsWith(".css")) {
items.push(
// deno-lint-ignore no-explicit-any
h("link", { rel: "stylesheet", href: asset(id) } as any),
);
}
}
if (Array.isArray(vnode.props.children)) {
vnode.props.children.push(...items);
} else if (
vnode.props.children !== null &&
typeof vnode.props.children === "object"
) {
// deno-lint-ignore no-explicit-any
items.push(vnode.props.children as any);
vnode.props.children = items;
} else {
vnode.props.children = items;
}
}
break;
}
case "body":
RENDER_STATE!.renderedHtmlBody = true;
break;
@@ -487,7 +517,6 @@ function FreshRuntimeScript() {
{ json: true },
);
// const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
const runtimeUrl = buildCache.clientEntry.startsWith(".")
? buildCache.clientEntry.slice(1)
: buildCache.clientEntry;
@@ -1,10 +1,10 @@
import type { VNode } from "preact";
import { ASSET_CACHE_BUST_KEY } from "../constants.ts";
export const DATA_CURRENT = "data-current";
export const DATA_ANCESTOR = "data-ancestor";
export const DATA_FRESH_KEY = "data-frsh-key";
export const CLIENT_NAV_ATTR = "f-client-nav";
export const ASSET_CACHE_BUST_KEY = "__frsh_c";
export const enum UrlMatchKind {
None,
+4
View File
@@ -163,6 +163,10 @@ export class MockBuildCache<State> implements BuildCache<State> {
this.#files = files;
}
getEntryAssets(): string[] {
return [];
}
getFsRoutes(): Command<State>[] {
return fsItemsToCommands(this.#files);
}