forked from vitejs/vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rewriteUrl.ts
37 lines (34 loc) · 1.05 KB
/
rewriteUrl.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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)
}
}