fix(vite): basePath handling for static assets (#3394)

closes #3391 

---
Generated PR message:

Fix base path handling for assets in plugin-vite

Fixes issue where Fresh apps mounted at non-root paths (e.g., /ui) in
frameworks like Hono would fail to load assets correctly.

  Problem

When mounting a Fresh app with app.mount('/ui', UI.fetch), the HTML
would load but all assets (CSS, JS, images) would return 404 because
asset paths
were hardcoded to start with /assets/ instead of respecting the Vite
base configuration.

  Solution

- Modified packages/plugin-vite/src/plugins/server_entry.ts to read
Vite's base config and apply it to asset paths
- Added getAssetPath() helper function to construct proper asset URLs
with base path
  - Updated both CSS and asset file registration to use the base path

  Testing

Added comprehensive test case "vite build - base path asset handling"
that:
  - Builds demo with custom base path /my-app/
  - Verifies generated server.js contains correctly prefixed asset paths
  - Follows existing test patterns and utilities

  Usage

  Users can now properly mount Fresh apps by configuring both:
```ts
  // vite.config.ts
  export default defineConfig({
    base: "/ui/",
    plugins: [fresh()],
  });

  // main.ts  
  const app = new App({ basePath: "/ui" });

  // hono-app.ts
  app.mount('/ui', UI.fetch); // Assets now work correctly
```

  Backward compatible - no changes needed for apps mounted at root path.
This commit is contained in:
fry69
2025-09-11 16:07:15 +02:00
committed by GitHub
parent 554644b240
commit 6fbe0ddcc4
3 changed files with 38 additions and 3 deletions
@@ -16,9 +16,19 @@ export function serverEntryPlugin(
let serverOutDir = "";
let clientOutDir = "";
let root = "";
let basePath = "";
let isDev = false;
const getAssetPath = (id: string): string => {
if (basePath === "/") {
return `/${id}`;
}
// Ensure basePath ends with / and construct the path manually to avoid platform-specific path issues
const normalizedBase = basePath.endsWith("/") ? basePath : basePath + "/";
return normalizedBase + id;
};
return {
name: "fresh:server_entry",
applyToEnvironment(env) {
@@ -29,6 +39,10 @@ export function serverEntryPlugin(
},
configResolved(config) {
root = config.root;
basePath = config.base || "/";
if (basePath !== "/" && !basePath.endsWith("/")) {
basePath += "/";
}
serverEntry = pathWithRoot(options.serverEntry, config.root);
serverOutDir = pathWithRoot(
config.environments.ssr.build.outDir,
@@ -98,7 +112,7 @@ if (import.meta.hot) import.meta.hot.accept();`;
staticFiles.push({
filePath: path.join(serverOutDir, id),
hash: null,
pathname: `/${id}`,
pathname: getAssetPath(id),
});
}
}
@@ -110,7 +124,7 @@ if (import.meta.hot) import.meta.hot.accept();`;
staticFiles.push({
filePath: path.join(serverOutDir, id),
hash: null,
pathname: `/${id}`,
pathname: getAssetPath(id),
});
}
}
+17
View File
@@ -447,3 +447,20 @@ Deno.test({
sanitizeOps: false,
sanitizeResources: false,
});
Deno.test({
name: "vite build - base path asset handling",
fn: async () => {
await using res = await buildVite(DEMO_DIR, { base: "/my-app/" });
// Read the generated server.js to check asset paths
const serverJs = await Deno.readTextFile(
path.join(res.tmp, "_fresh", "server.js"),
);
// Asset paths should include the base path /my-app/
expect(serverJs).toContain('"/my-app/assets/');
},
sanitizeOps: false,
sanitizeResources: false,
});
+5 -1
View File
@@ -131,7 +131,10 @@ export async function withDevServer(
await launchDevServer(tmp.dir, fn, env);
}
export async function buildVite(fixtureDir: string) {
export async function buildVite(
fixtureDir: string,
options?: { base?: string },
) {
const tmp = await withTmpDir({
dir: path.join(import.meta.dirname!, ".."),
prefix: "tmp_vite_",
@@ -140,6 +143,7 @@ export async function buildVite(fixtureDir: string) {
const builder = await createBuilder({
logLevel: "error",
root: fixtureDir,
base: options?.base,
build: {
emptyOutDir: true,
},