Skip to content

Commit

Permalink
feat: option to disable SPA catch-all
Browse files Browse the repository at this point in the history
  • Loading branch information
brillout committed May 7, 2022
1 parent 9f8381e commit aee24d9
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
8 changes: 8 additions & 0 deletions packages/vite/src/node/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,14 @@ export interface CommonServerOptions {
* Specify server response headers.
*/
headers?: HttpServerHeaders
/**
* Disable SPA catch-all routing.
*
* By default, Vite's dev/preview server redirects all routes to the root
* URL `/`. (In order to enable client-side routed SPAs.) For SSR or MPA apps,
* this behavior should be disabled and this option allows you to do so.
*/
disableSPACatchAll?: boolean
}

/**
Expand Down
20 changes: 18 additions & 2 deletions packages/vite/src/node/preview.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import path from 'path'
import fs from 'fs'
import sirv from 'sirv'
import connect from 'connect'
import compression from './server/middlewares/compression'
Expand Down Expand Up @@ -35,7 +36,8 @@ export function resolvePreviewOptions(
open: preview?.open ?? server.open,
proxy: preview?.proxy ?? server.proxy,
cors: preview?.cors ?? server.cors,
headers: preview?.headers ?? server.headers
headers: preview?.headers ?? server.headers,
disableSPACatchAll: preview?.disableSPACatchAll ?? server.disableSPACatchAll
}
}

Expand Down Expand Up @@ -100,19 +102,33 @@ export async function preview(
app.use(compression())

// static assets
const { disableSPACatchAll } = config.preview
const distDir = path.resolve(config.root, config.build.outDir)
app.use(
config.base,
sirv(distDir, {
etag: true,
dev: true,
single: true
single: !disableSPACatchAll
})
)

// apply post server hooks from plugins
postHooks.forEach((fn) => fn && fn())

// 404 handling
if (disableSPACatchAll) {
app.use(config.base, (_, res, next) => {
const file = path.join(distDir, './404.html')
if (fs.existsSync(file)) {
res.statusCode = 404
res.end(fs.readFileSync(file))
} else {
next()
}
})
}

const options = config.preview
const hostname = resolveHostname(options.host)
const port = options.port ?? 4173
Expand Down
5 changes: 4 additions & 1 deletion packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,10 @@ export async function createServer(
middlewares.use(serveStaticMiddleware(root, server))

// spa fallback
if (!middlewareMode || middlewareMode === 'html') {
if (
!serverConfig.disableSPACatchAll &&
(!middlewareMode || middlewareMode === 'html')
) {
middlewares.use(spaFallbackMiddleware(root))
}

Expand Down

0 comments on commit aee24d9

Please sign in to comment.