forked from vitejs/vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spaFallback.ts
32 lines (30 loc) · 959 Bytes
/
spaFallback.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
import fs from 'fs'
import history from 'connect-history-api-fallback'
import path from 'path'
import { Connect } from 'types/connect'
import { createDebugger } from '../../utils'
export function spaFallbackMiddleware(
root: string
): Connect.NextHandleFunction {
const historySpaFallbackMiddleware = history({
logger: createDebugger('vite:spa-fallback'),
// support /dir/ without explicit index.html
rewrites: [
{
from: /\/$/,
to({ parsedUrl }: any) {
const rewritten = parsedUrl.pathname + 'index.html'
if (fs.existsSync(path.join(root, rewritten))) {
return rewritten
} else {
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)
}
}