Skip to content

Commit

Permalink
chore: improve naming
Browse files Browse the repository at this point in the history
  • Loading branch information
brillout committed Aug 27, 2022
1 parent 0d8320d commit d170896
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ import type { WebSocketServer } from './ws'
import { createWebSocketServer } from './ws'
import { baseMiddleware } from './middlewares/base'
import { proxyMiddleware } from './middlewares/proxy'
import { spaFallbackMiddleware } from './middlewares/spaFallback'
import { rewriteUrlMiddleware } from './middlewares/rewriteUrl'
import { transformMiddleware } from './middlewares/transform'
import {
createDevHtmlTransformFn,
Expand Down Expand Up @@ -543,7 +543,7 @@ export async function createServer(

// spa fallback
if (config.appType === 'spa' || config.appType === 'mpa') {
middlewares.use(spaFallbackMiddleware(root, config.appType === 'spa'))
middlewares.use(rewriteUrlMiddleware(root, config.appType === 'spa'))
}

// run post config hooks
Expand Down
37 changes: 37 additions & 0 deletions packages/vite/src/node/server/middlewares/rewriteUrl.ts
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)
}
}

0 comments on commit d170896

Please sign in to comment.