Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: spa option, preview and dev for MPA and SSR apps #8217

Merged
merged 21 commits into from May 23, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/config/index.md
Expand Up @@ -462,6 +462,13 @@ export default defineConfig(({ command, mode }) => {
`envPrefix` should not be set as `''`, which will expose all your env variables and cause unexpected leaking of of sensitive information. Vite will throw error when detecting `''`.
:::

### isSPA

- **Type:** `boolean`
- **Default:** `true`

This toggles the SPA catch-all routing of the development and preview server: by default, all URLs are rendered to the same single page (in order to enable SPA client-side routing). For SSR and MPA apps, this behavior can be disabled by setting `isSPA` to `false`.

## Server Options

### server.host
Expand Down
11 changes: 11 additions & 0 deletions packages/vite/src/node/config.ts
Expand Up @@ -204,6 +204,15 @@ export interface UserConfig {
'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures'
>
}
/**
* Whether the app is a SPA.
* This toggles the SPA catch-all routing of the development and preview
* server: by default, all URLs are rendered to the same single page (in order
* to enable SPA client-side routing). For SSR and MPA apps, this behavior can
* be disabled by setting `isSPA` to `false`.
* @default true
*/
isSPA?: boolean
}

export interface ExperimentalOptions {
Expand Down Expand Up @@ -469,6 +478,8 @@ export async function resolveConfig(

const optimizeDeps = config.optimizeDeps || {}

config.isSPA ??= true
brillout marked this conversation as resolved.
Show resolved Hide resolved

const resolved: ResolvedConfig = {
...config,
configFile: configFile ? normalizePath(configFile) : undefined,
Expand Down
30 changes: 27 additions & 3 deletions packages/vite/src/node/preview.ts
@@ -1,5 +1,6 @@
import path from 'path'
import type * as http from 'http'
import fs from 'fs'
brillout marked this conversation as resolved.
Show resolved Hide resolved
import sirv from 'sirv'
import connect from 'connect'
import type { Connect } from 'types/connect'
Expand Down Expand Up @@ -97,19 +98,42 @@ export async function preview(

app.use(compression())

const { isSPA } = config

if (isSPA) {
// We need to apply the plugins' server post hooks before `sirv()`. (Because
// `sirv(_, { single: true })` catches all routes and plugin middlewares
// would never run.)
postHooks.forEach((fn) => fn && fn())
}

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

// apply post server hooks from plugins
postHooks.forEach((fn) => fn && fn())
if (!isSPA) {
// We apply the plugins' server post hooks after `sirv()` so that `sirv()`
// can serve pre-rendered pages before any SSR middleware.
postHooks.forEach((fn) => fn && fn())
brillout marked this conversation as resolved.
Show resolved Hide resolved

// 404 handling (this simulates what most static hosts do)
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)
Expand Down
25 changes: 15 additions & 10 deletions packages/vite/src/node/server/index.ts
Expand Up @@ -503,20 +503,25 @@ export async function createServer(
middlewares.use(serveRawFsMiddleware(server))
middlewares.use(serveStaticMiddleware(root, server))

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

// run post config hooks
// This is applied before the html middleware so that user middleware can
// serve custom content instead of index.html.
// We need to apply post server hooks before `spaFallbackMiddleware()`.
brillout marked this conversation as resolved.
Show resolved Hide resolved
// (Because `spaFallbackMiddleware()` catches all routes and plugin
// middlewares would never run.)
postHooks.forEach((fn) => fn && fn())

if (!middlewareMode || middlewareMode === 'html') {
const isMiddlewareModeSSR = middlewareMode && middlewareMode !== 'html'

if (config.isSPA && !isMiddlewareModeSSR) {
// SPA catch-all fallback routing
middlewares.use(spaFallbackMiddleware(root))
// transform index.html
brillout marked this conversation as resolved.
Show resolved Hide resolved
middlewares.use(indexHtmlMiddleware(server))
// handle 404s
}

// Handle 404s.
// We keep 404 handling when `config.isSPA === false` because some SSR tools,
// such as vite-plugin-ssr, cannot always render 404 pages. (E.g. if the
// vite-plugin-ssr user didn't define a `_error.page.js`.)
if (!isMiddlewareModeSSR) {
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
middlewares.use(function vite404Middleware(_, res) {
res.statusCode = 404
Expand Down