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
@@ -1,22 +1,40 @@
import type { Plugin } from "vite";
import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts";
export function clientEntryPlugin(): Plugin {
export function clientEntryPlugin(options: ResolvedFreshViteConfig): Plugin {
const modName = "fresh:client-entry";
const modNameUser = "fresh:client-entry-user";
let clientEntry = "";
return {
name: "fresh:client-entry",
applyToEnvironment(env) {
return env.name === "client";
},
configResolved(config) {
clientEntry = pathWithRoot(options.clientEntry, config.root);
},
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
} else if (id === modNameUser) {
return clientEntry;
}
},
load(id) {
async load(id) {
if (id !== `\0${modName}`) return;
let exists = false;
try {
const stat = await Deno.stat(clientEntry);
exists = stat.isFile;
} catch {
exists = false;
}
return `export * from "fresh/runtime-client";
${exists ? `import "fresh:client-entry-user";` : ""}
if (import.meta.hot) {
import.meta.hot.accept(() => {
+57 -22
View File
@@ -8,6 +8,7 @@ import {
import * as path from "@std/path";
import * as babel from "@babel/core";
import babelReact from "@babel/preset-react";
import { httpAbsolute } from "./patches/http_absolute.ts";
interface DenoState {
type: RequestedModuleType;
@@ -43,17 +44,30 @@ export function deno(): Plugin {
async resolveId(id, importer, options) {
const loader = options?.ssr ? ssrLoader : browserLoader;
const original = id;
let isHttp = false;
if (id.startsWith("deno-http::")) {
isHttp = true;
id = id.slice("deno-http::".length);
}
importer = isDenoSpecifier(importer)
? parseDenoSpecifier(importer).specifier
: importer;
if (id.startsWith("/") && importer && /^https?:\/\//g.test(importer)) {
const url = new URL(importer);
id = `${url.origin}${id}`;
}
// We still want to allow other plugins to participate in
// resolution, with us being in front due to `enforce: "pre"`.
// But we still want to ignore everything `vite:resolve` does
// because we're kinda replacing that plugin here.
const tmp = await this.resolve(id, importer, options);
if (tmp && tmp.resolvedBy !== "vite:resolve") {
if (tmp.external) {
if (tmp.external && !/^https?:\/\//.test(tmp.id)) {
return tmp;
}
@@ -66,7 +80,7 @@ export function deno(): Plugin {
}
// Plugins may return lower cased drive letters on windows
if (path.isAbsolute(id)) {
if (!isHttp && path.isAbsolute(id)) {
id = path.toFileUrl(path.normalize(id))
.href;
}
@@ -83,7 +97,7 @@ export function deno(): Plugin {
ResolutionMode.Import,
);
if (id === resolved) {
if (original === resolved) {
return null;
}
@@ -124,7 +138,7 @@ export function deno(): Plugin {
const code = new TextDecoder().decode(result.code);
const maybeJsx = maybeTransformJsxBrowser({
const maybeJsx = babelTransform({
ssr: !!options?.ssr,
code,
id: specifier,
@@ -150,6 +164,14 @@ export function deno(): Plugin {
if (meta === null || meta === undefined) return;
// Skip for non-js files like `.css`
if (
meta.type === RequestedModuleType.Default &&
!/\.([tj]sx?|[mc]?[tj]s)$/.test(id)
) {
return;
}
const url = path.toFileUrl(id);
const result = await loader.load(url.href, meta.type);
@@ -159,7 +181,7 @@ export function deno(): Plugin {
const code = new TextDecoder().decode(result.code);
const maybeJsx = maybeTransformJsxBrowser({
const maybeJsx = babelTransform({
ssr: !!options?.ssr,
id,
code,
@@ -263,31 +285,44 @@ function getDenoType(id: string, type: string): RequestedModuleType {
}
}
function maybeTransformJsxBrowser(
function babelTransform(
options: { ssr: boolean; code: string; id: string; isDev: boolean },
) {
if (
!/\.([tj]sx?|[mc[jt]s)$/.test(options.id) &&
!/^https?:\/\//.test(options.id)
) {
return null;
}
const { ssr, code, id, isDev } = options;
const presets: babel.PluginItem[] = [];
if (
!ssr && id.endsWith(".tsx") || id.endsWith(".jsx")
) {
const babelResult = babel.transformSync(code, {
filename: id,
babelrc: false,
sourceMaps: "inline",
presets: [[babelReact, {
runtime: "automatic",
importSource: "preact",
development: isDev,
}]],
});
presets.push([babelReact, {
runtime: "automatic",
importSource: "preact",
development: isDev,
}]);
}
if (babelResult !== null && babelResult.code) {
return {
code: babelResult.code,
map: babelResult.map,
};
}
const url = URL.canParse(id) ? new URL(id) : null;
const result = babel.transformSync(code, {
filename: id,
babelrc: false,
sourceMaps: "inline",
presets: presets,
plugins: [httpAbsolute(url)],
});
if (result !== null && result.code) {
return {
code: result.code,
map: result.map,
};
}
return null;
+19 -14
View File
@@ -1,17 +1,12 @@
import type { Plugin } from "vite";
import { nodeToRequest, responseToNode } from "../request.ts";
import * as path from "@std/path";
import { pathWithRoot } from "../utils.ts";
import { ASSET_CACHE_BUST_KEY } from "fresh/internal";
export function devServer(): Plugin[] {
let publicDir = "";
return [
{
name: "fresh:dev_server",
configResolved(cfg) {
publicDir = pathWithRoot(cfg.publicDir, cfg.root);
},
configureServer(server) {
const IGNORE_URLS = /^\/(@(vite|fs|id)|\.vite)\//;
@@ -25,26 +20,25 @@ export function devServer(): Plugin[] {
`${protocol}://${host}:${port}${nodeReq.url ?? "/"}`,
);
// Don't cache in dev
url.searchParams.delete(ASSET_CACHE_BUST_KEY);
// Check if it's a vite url
if (
IGNORE_URLS.test(url.pathname) ||
server.environments.client.moduleGraph.urlToModuleMap.has(
url.pathname,
)
) ||
url.pathname === "/.well-known/appspecific/com.chrome.devtools.json"
) {
return next();
}
// Check if it's a static file first
// FIXME: Should this still go through fresh?
if (url.pathname !== "/") {
try {
await Deno.stat(path.join(publicDir, url.pathname));
const ext = path.extname(url.pathname);
if (ext !== "") {
return next();
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
return next(err);
}
}
}
@@ -72,6 +66,17 @@ export function devServer(): Plugin[] {
if (clientMod === undefined) {
options.server.hot.send("fresh:reload");
return;
}
const ssrMod = options.server.environments.ssr.moduleGraph
.getModulesByFile(options.file);
if (ssrMod !== undefined) {
// SSR-only module. Might still be a route.
// deno-lint-ignore no-console
console.log("hmr", options.file);
options.server.hot.send("fresh:reload");
}
},
},
@@ -17,6 +17,8 @@ export function patches(): Plugin {
return true;
},
transform(code, id, options) {
if (!/\.([tj]sx?|[mc][tj]s)$/.test(id)) return;
const presets = [];
if (!options?.ssr && /\.(tsx?|m[jt]s)$/.test(id)) {
presets.push([babelReact, {
@@ -1,8 +1,8 @@
import type { types } from "@babel/core";
import type { PluginObj, types } from "@babel/core";
export function cjsPlugin(
{ types: t }: { types: typeof types },
): babel.PluginObj {
): PluginObj {
const HAS_ES_MODULE = "esModule";
const REQUIRE_CALLS = "requireCalls";
const ROOT_SCOPE = "rootScope";
@@ -0,0 +1,66 @@
import type {
NodePath,
PluginObj,
PluginPass,
types,
Visitor,
} from "@babel/core";
function maybeRewrite(
t: typeof types,
path: NodePath,
source: string,
url: URL,
) {
if (source.startsWith("/")) {
const s = `deno-http::${url.origin}${source}`;
path.replaceWith(t.stringLiteral(s));
} else if (/^https?:\/\//.test(source)) {
const s = `deno-http::${source}`;
path.replaceWith(t.stringLiteral(s));
}
}
export function httpAbsolute(url: URL | null) {
return ({ types: t }: { types: typeof types }): PluginObj => {
const visitor: Visitor<PluginPass> = url !== null
? {
ImportDeclaration(path) {
const source = path.node.source.value;
maybeRewrite(t, path.get("source"), source, url);
},
ExportAllDeclaration(path) {
const source = path.node.source.value;
maybeRewrite(t, path.get("source"), source, url);
},
ExportNamedDeclaration(path) {
if (!path.node.source) return;
const source = path.node.source.value;
// deno-lint-ignore no-explicit-any
maybeRewrite(t, path.get("source") as any, source, url);
},
CallExpression(path) {
if (
t.isImport(path.node.callee) && path.node.arguments.length > 0 &&
t.isStringLiteral(path.node.arguments[0])
) {
const source = path.node.arguments[0].value;
maybeRewrite(
t,
path
.get("arguments")[0],
source,
url,
);
}
},
}
: {};
return {
name: "fresh-http-absolute",
visitor,
};
};
}
@@ -0,0 +1,46 @@
import { expect } from "@std/expect/expect";
import * as babel from "@babel/core";
import { httpAbsolute } from "./http_absolute.ts";
function runTest(options: { input: string; expected: string; url?: URL }) {
const res = babel.transformSync(options.input, {
filename: "foo.js",
babelrc: false,
plugins: [httpAbsolute(options.url ?? null)],
});
const output = res?.code ?? "";
expect(output).toEqual(options.expected);
}
Deno.test("http absolute - change import sources", () => {
runTest({
input: `import foo from "/foo.js"`,
expected: `import foo from "deno-http::http://localhost/foo.js";`,
url: new URL("http://localhost"),
});
});
Deno.test("http absolute - change export all sources", () => {
runTest({
input: `export * as foo from "/foo.js"`,
expected: `export * as foo from "deno-http::http://localhost/foo.js";`,
url: new URL("http://localhost"),
});
});
Deno.test("http absolute - change export sources", () => {
runTest({
input: `export { foo } from "/foo.js"`,
expected: `export { foo } from "deno-http::http://localhost/foo.js";`,
url: new URL("http://localhost"),
});
});
Deno.test("http absolute - change import()", () => {
runTest({
input: `import("/foo.js")`,
expected: `import("deno-http::http://localhost/foo.js");`,
url: new URL("http://localhost"),
});
});
@@ -1,4 +1,4 @@
import type { NodePath, types } from "@babel/core";
import type { NodePath, PluginObj, types } from "@babel/core";
export function inlineEnvVarsPlugin(mode: string) {
const allowed = new Map<string, string>();
@@ -12,7 +12,7 @@ export function inlineEnvVarsPlugin(mode: string) {
return (
{ types: t }: { types: typeof types },
): babel.PluginObj => {
): PluginObj => {
function replace(path: NodePath, name: string) {
if (allowed.has(name)) {
const value = allowed.get(name);
@@ -1,6 +1,6 @@
import type { types } from "@babel/core";
import type { PluginObj, types } from "@babel/core";
export function jsxComments(): babel.PluginObj {
export function jsxComments(): PluginObj {
return {
name: "fresh-jsx-comment",
visitor: {
@@ -1,5 +1,9 @@
import type { Plugin } from "vite";
import { generateServerEntry } from "fresh/internal-dev";
import type { Manifest, Plugin } from "vite";
import {
generateServerEntry,
type PendingStaticFile,
prepareStaticFile,
} from "fresh/internal-dev";
import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts";
import * as path from "@std/path";
@@ -10,6 +14,7 @@ export function serverEntryPlugin(
let serverEntry = "";
let serverOutDir = "";
let clientOutDir = "";
let root = "";
let isDev = false;
@@ -29,6 +34,10 @@ export function serverEntryPlugin(
config.environments.ssr.build.outDir,
config.root,
);
clientOutDir = pathWithRoot(
config.environments.client.build.outDir,
config.root,
);
},
resolveId(id) {
if (id === modName) {
@@ -39,22 +48,71 @@ export function serverEntryPlugin(
if (id !== `\0${modName}`) return;
let code = generateServerEntry({
root: path.relative(serverOutDir, root),
root: isDev ? path.relative(serverOutDir, root) : "..",
serverEntry: path.toFileUrl(serverEntry).href,
snapshotSpecifier: "fresh:server-snapshot",
});
code += `
export function registerStaticFile(prepared) {
snapshot.staticFiles.set(prepared.name, {
name: prepared.name,
contentType: prepared.contentType,
filePath: prepared.filePath
});
}
`;
if (isDev) {
code += `if (import.meta.hot) import.meta.hot.accept();\n`;
}
return code;
},
async writeBundle() {
async writeBundle(_options, bundle) {
const manifest = bundle[".vite/manifest.json"];
const staticFiles: PendingStaticFile[] = [];
if (
manifest && manifest.type === "asset" &&
typeof manifest.source === "string"
) {
const json = JSON.parse(manifest.source) as Manifest;
for (const item of Object.values(json)) {
if (item.assets) {
for (let i = 0; i < item.assets.length; i++) {
const id = item.assets[i];
staticFiles.push({
filePath: path.join(serverOutDir, id),
hash: null,
pathname: `/${id}`,
});
}
}
}
}
const registered = await Promise.all(staticFiles.map(async (file) => {
const prepared = await prepareStaticFile(file, serverOutDir);
const rel = path.relative(serverOutDir, file.filePath);
const target = path.join(clientOutDir, rel);
await Deno.rename(file.filePath, target);
prepared.filePath = path.join("client", prepared.filePath);
return `registerStaticFile(${JSON.stringify(prepared)});`;
}));
const outDir = path.dirname(serverOutDir);
await Deno.writeTextFile(
path.join(outDir, "server.js"),
`import server from "./server/server-entry.mjs";
`import server, { registerStaticFile } from "./server/server-entry.mjs";
${registered.join("\n")}
export default {
fetch: server.fetch
};
@@ -77,6 +77,7 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
let islandMods: IslandModChunk[] = [];
let clientEntry = "/@id/fresh:client-entry";
let buildId = "";
const entryAssets: string[] = [];
if (isDev && server !== undefined) {
for (const id of islands.keys()) {
@@ -104,8 +105,10 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
),
) as Manifest;
const clientEntryName = "client-entry";
for (const chunk of Object.values(manifest)) {
if (chunk.name === "client-entry") {
if (chunk.name === clientEntryName) {
clientEntry = pathToSpec(clientOutDir, chunk.file);
}
@@ -115,6 +118,24 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
hash: null,
});
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 ?? []) {
@@ -165,10 +186,11 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
}
const code = await generateSnapshotServer({
outDir: root,
outDir: path.join(clientOutDir, ".."),
staticFiles,
buildId,
clientEntry,
entryAssets,
fsRoutesFiles: result.routes,
islands: islandMods,
writeSpecifier: (file) => {