-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
39 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import fs from 'node:fs' | ||
import path from 'node:path' | ||
import history from 'connect-history-api-fallback' | ||
import type { Connect } from 'types/connect' | ||
import { createDebugger } from '../../utils' | ||
|
||
export function rewriteUrlMiddleware( | ||
root: string, | ||
spaFallback: boolean | ||
): Connect.NextHandleFunction { | ||
const historySpaFallbackMiddleware = history({ | ||
logger: createDebugger('vite:spa-fallback'), | ||
// support /dir/ without explicit index.html | ||
rewrites: [ | ||
{ | ||
from: /\/$/, | ||
to({ parsedUrl }: any) { | ||
const rewritten = | ||
decodeURIComponent(parsedUrl.pathname) + 'index.html' | ||
|
||
if (fs.existsSync(path.join(root, rewritten))) { | ||
return rewritten | ||
} else { | ||
if (spaFallback) { | ||
return `/index.html` | ||
} | ||
} | ||
} | ||
} | ||
] | ||
}) | ||
|
||
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` | ||
return function viteSpaFallbackMiddleware(req, res, next) { | ||
return historySpaFallbackMiddleware(req, res, next) | ||
} | ||
} |