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 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/config/index.md
Original file line number Diff line number Diff line change
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 `''`.
:::

### spa

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

This configuration is meant for framework authors, or users using Vite's SSR API. See [SSR - Vite CLI](/guide/ssr#vite-cli).
brillout marked this conversation as resolved.
Show resolved Hide resolved

## Server Options

### server.host
Expand Down
11 changes: 11 additions & 0 deletions docs/guide/ssr.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,3 +264,14 @@ In some cases like `webworker` runtimes, you might want to bundle your SSR build

- Treat all dependencies as `noExternal`
- Throw an error if any Node.js built-ins are imported

## Vite CLI

The CLI commands `$ vite dev` and `$ vite preview` can also be used for SSR apps:

1. Add your SSR middleware to the development server with [`configureServer`](/guide/api-plugin.html#configureserver) and to the preview server with [`configurePreviewServer`](/guide/api-plugin.html#configurepreviewserver).
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
:::tip Note
Use a post hook so that your SSR middleware runs _after_ Vite's middlewares.
:::

2. Set `config.spa` to `false`. This switches the development and preview server from SPA mode to SSR mode.
9 changes: 8 additions & 1 deletion packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,11 @@ export interface UserConfig {
'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures'
>
}
/**
* This configuration is meant for framework authors, or users using Vite's
* SSR API.
*/
spa?: boolean
}

export interface ExperimentalOptions {
Expand Down Expand Up @@ -270,6 +275,7 @@ export type ResolvedConfig = Readonly<
/** @internal */
packageCache: PackageCache
worker: ResolveWorkerOptions
spa: boolean
}
>

Expand Down Expand Up @@ -510,7 +516,8 @@ export async function resolveConfig(
...optimizeDeps.esbuildOptions
}
},
worker: resolvedWorkerOptions
worker: resolvedWorkerOptions,
spa: config.spa ?? true
}

// flat config.worker.plugin
Expand Down
29 changes: 26 additions & 3 deletions packages/vite/src/node/preview.ts
Original file line number Diff line number Diff line change
@@ -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,41 @@ export async function preview(

app.use(compression())

const { spa } = config

if (spa) {
// We need to apply the plugins' server post hooks before `sirv()`. (Because
// `sirv(_, { single: true })` catches all routes.)
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: spa
})
)

// apply post server hooks from plugins
postHooks.forEach((fn) => fn && fn())
if (!spa) {
brillout marked this conversation as resolved.
Show resolved Hide resolved
// 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
27 changes: 16 additions & 11 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,21 +503,26 @@ 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.)
postHooks.forEach((fn) => fn && fn())

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

if (config.spa && !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
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
}

// Handle 404s.
// We keep 404 handling when `config.spa === 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
res.end()
Expand Down