Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: give history middleware a name (#4908)
* chore: give history middleware a name * chore: move spa fallback middleware to new file * Update packages/vite/src/node/server/middlewares/spaFallback.ts Co-authored-by: patak <matias.capeletto@gmail.com> * fix: typo * chore: better naming for impl function Co-authored-by: patak <matias.capeletto@gmail.com>
- Loading branch information
Showing
2 changed files
with
35 additions
and
21 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,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) | ||
} | ||
} |