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!: appType (spa, mpa, custom), boolean middlewareMode #8452

Merged
merged 25 commits into from Jun 18, 2022
Merged
Show file tree
Hide file tree
Changes from 14 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
17 changes: 8 additions & 9 deletions docs/config/server-options.md
Expand Up @@ -153,14 +153,12 @@ export default defineConfig({

## server.middlewareMode

- **Type:** `'ssr' | 'html'`

Create Vite server in middleware mode. (without a HTTP server)
- **Type:** `boolean`
- **Default:** `false`

- `'ssr'` will disable Vite's own HTML serving logic so that you should serve `index.html` manually.
- `'html'` will enable Vite's own HTML serving logic.
Create Vite server in middleware mode
patak-dev marked this conversation as resolved.
Show resolved Hide resolved

- **Related:** [SSR - Setting Up the Dev Server](/guide/ssr#setting-up-the-dev-server)
- **Related:** [appType](./shared-options#apptype), [SSR - Setting Up the Dev Server](/guide/ssr#setting-up-the-dev-server)

- **Example:**

Expand All @@ -173,14 +171,15 @@ async function createServer() {

// Create Vite server in middleware mode.
const vite = await createViteServer({
server: { middlewareMode: 'ssr' }
server: { middlewareMode: true },
appType: 'custom'
})
// Use vite's connect instance as middleware
app.use(vite.middlewares)

app.use('*', async (req, res) => {
// If `middlewareMode` is `'ssr'`, should serve `index.html` here.
// If `middlewareMode` is `'html'`, there is no need to serve `index.html`
// If `appType` is `'custom'`, should serve response here.
// If `appType` is `'spa'` or `'mpa'`, there is no need to serve `index.html`
// because Vite will do that.
})
}
Expand Down
14 changes: 10 additions & 4 deletions docs/config/shared-options.md
Expand Up @@ -336,9 +336,15 @@ Env variables starts with `envPrefix` will be exposed to your client source code
`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
## appType

- **Type:** `boolean`
- **Default:** `true`
- **Type:** `'spa' | 'mpa' | 'custom'`
- **Default:** `'spa'`

Whether your application is a Single Page Application (SPA), a [Multi Page Application (MPA)](../guide/build#multi-page-app), or Custom Application (SSR and frameworks with custom HTML handling):

- `'spa'`: include SPA fallback middleware and configure [sirv](https://github.com/lukeed/sirv) with `single: true` in preview
- `'mpa'`: only include non-SPA HTML middlewares
- `'custom'`: don't include HTML middlewares

Whether your application is a Single Page Application (SPA). Set to `false` for other kinds of apps like MPAs. Learn more in Vite's [SSR guide](/guide/ssr#vite-cli).
Learn more in Vite's [SSR guide](/guide/ssr#vite-cli). Related: [`server.middlewareMode`](./server-options#servermiddlewaremode).
17 changes: 7 additions & 10 deletions docs/guide/ssr.md
Expand Up @@ -78,9 +78,10 @@ async function createServer() {
// serving logic and let the parent server take control.
//
// In middleware mode, if you want to use Vite's own HTML serving logic
// use `'html'` as the `middlewareMode` (ref https://vitejs.dev/config/#server-middlewaremode)
// use `appType: 'spa' | 'mpa'`
const vite = await createViteServer({
server: { middlewareMode: 'ssr' }
server: { middlewareMode: true },
appType: 'custom'
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
Expand Down Expand Up @@ -267,11 +268,7 @@ In some cases like `webworker` runtimes, you might want to bundle your SSR build

## 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#configureserver) and to the preview server with [`configurePreviewServer`](/guide/api-plugin#configurepreviewserver).
:::tip Note
Use a post hook so that your SSR middleware runs _after_ Vite's middlewares.
:::

patak-dev marked this conversation as resolved.
Show resolved Hide resolved
2. Set `config.spa` to `false`. This switches the development and preview server from SPA mode to SSR/MPA mode.
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
The CLI commands `$ vite dev` and `$ vite preview` can also be used for SSR apps you can add your SSR middleware to the development server with [`configureServer`](/guide/api-plugin#configureserver) and to the preview server with [`configurePreviewServer`](/guide/api-plugin#configurepreviewserver).
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
:::tip Note
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
Use a post hook so that your SSR middleware runs _after_ Vite's middlewares.
:::
23 changes: 17 additions & 6 deletions packages/vite/src/node/config.ts
Expand Up @@ -51,6 +51,13 @@ export interface ConfigEnv {
mode: string
}

/**
* spa: include SPA fallback middleware and configure sirv with `single: true` in preview
* mpa: only include non-SPA HTML middlewares
* custom: don't include HTML middlewares
*/
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
export type AppType = 'spa' | 'mpa' | 'custom'

export type UserConfigFn = (env: ConfigEnv) => UserConfig | Promise<UserConfig>
export type UserConfigExport = UserConfig | Promise<UserConfig> | UserConfigFn

Expand Down Expand Up @@ -211,11 +218,12 @@ export interface UserConfig {
>
}
/**
* Whether your application is a Single Page Application (SPA). Set to `false`
* for other kinds of apps like MPAs.
* @default true
* Whether your application is a Single Page Application (SPA),
* a Multi-Page Application (MPA), or Custom Application (SSR
* and frameworks with custom HTML handling)
* @default 'spa'
*/
spa?: boolean
appType?: AppType
}

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

Expand Down Expand Up @@ -536,7 +544,10 @@ export async function resolveConfig(
}
},
worker: resolvedWorkerOptions,
spa: config.spa ?? true
appType:
config.appType ?? config?.server?.middlewareMode === 'ssr'
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

middlewareMode is a boolean now

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is for backward compat. We can break it directly for v3 thought

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think they are only a handful of frameworks out there using middlewareMode: 'ssr' now that it should be safe to break. Otherwise another option is to log a warning, but framework authors would likely fix it right away so that end-users don't see it.

? 'custom'
: 'spa'
}

// flat config.worker.plugin
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/preview.ts
Expand Up @@ -104,7 +104,7 @@ export async function preview(
sirv(distDir, {
etag: true,
dev: true,
single: config.spa
single: config.appType === 'spa'
})
)

Expand Down
19 changes: 8 additions & 11 deletions packages/vite/src/node/server/index.ts
Expand Up @@ -100,6 +100,7 @@ export interface ServerOptions extends CommonServerOptions {

export interface ResolvedServerOptions extends ServerOptions {
fs: Required<FileSystemServeOptions>
middlewareMode: boolean
}

export interface FileSystemServeOptions {
Expand Down Expand Up @@ -268,10 +269,7 @@ export async function createServer(
config.server.https,
config.cacheDir
)
let { middlewareMode } = serverConfig
if (middlewareMode === true) {
middlewareMode = 'ssr'
}
const { middlewareMode } = serverConfig

const middlewares = connect() as Connect.Server
const httpServer = middlewareMode
Expand Down Expand Up @@ -487,10 +485,8 @@ export async function createServer(
middlewares.use(serveRawFsMiddleware(server))
middlewares.use(serveStaticMiddleware(root, server))

const isMiddlewareMode = middlewareMode && middlewareMode !== 'html'

// spa fallback
if (config.spa && !isMiddlewareMode) {
if (config.appType === 'spa' && !middlewareMode) {
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
middlewares.use(spaFallbackMiddleware(root))
}

Expand All @@ -499,12 +495,12 @@ export async function createServer(
// serve custom content instead of index.html.
postHooks.forEach((fn) => fn && fn())

if (config.spa && !isMiddlewareMode) {
if (config.appType !== 'custom' && !middlewareMode) {
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
// transform index.html
middlewares.use(indexHtmlMiddleware(server))
}

if (!isMiddlewareMode) {
bluwy marked this conversation as resolved.
Show resolved Hide resolved
if (!middlewareMode) {
// handle 404s
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
middlewares.use(function vite404Middleware(_, res) {
Expand All @@ -514,7 +510,7 @@ export async function createServer(
}

// error handler
middlewares.use(errorMiddleware(server, !!middlewareMode))
middlewares.use(errorMiddleware(server, middlewareMode))

const initOptimizer = async () => {
if (isDepsOptimizerEnabled(config)) {
Expand Down Expand Up @@ -652,7 +648,8 @@ export function resolveServerOptions(
): ResolvedServerOptions {
const server: ResolvedServerOptions = {
preTransformRequests: true,
...(raw as ResolvedServerOptions)
...(raw as ResolvedServerOptions),
middlewareMode: !!raw?.middlewareMode
}
let allowDirs = server.fs?.allow
const deny = server.fs?.deny || ['.env', '.env.*', '*.{crt,pem}']
Expand Down
3 changes: 2 additions & 1 deletion playground/json/server.js
Expand Up @@ -20,14 +20,15 @@ async function createServer(
root,
logLevel: isTest ? 'error' : 'info',
server: {
middlewareMode: 'ssr',
middlewareMode: true,
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
usePolling: true,
interval: 100
}
},
appType: 'custom',
json: {
stringify: true
}
Expand Down
5 changes: 3 additions & 2 deletions playground/optimize-missing-deps/server.js
Expand Up @@ -17,11 +17,12 @@ async function createServer(root = process.cwd(), hmrPort) {
root,
logLevel: isTest ? 'error' : 'info',
server: {
middlewareMode: 'ssr',
middlewareMode: true,
hmr: {
port: hmrPort
}
}
},
appType: 'custom'
})
app.use(vite.middlewares)

Expand Down
5 changes: 3 additions & 2 deletions playground/ssr-deps/server.js
Expand Up @@ -22,7 +22,7 @@ export async function createServer(root = process.cwd(), hmrPort) {
root,
logLevel: isTest ? 'error' : 'info',
server: {
middlewareMode: 'ssr',
middlewareMode: true,
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
Expand All @@ -32,7 +32,8 @@ export async function createServer(root = process.cwd(), hmrPort) {
hmr: {
port: hmrPort
}
}
},
appType: 'custom'
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
Expand Down
5 changes: 3 additions & 2 deletions playground/ssr-html/server.js
Expand Up @@ -37,7 +37,7 @@ export async function createServer(root = process.cwd(), hmrPort) {
root,
logLevel: isTest ? 'error' : 'info',
server: {
middlewareMode: 'ssr',
middlewareMode: true,
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
Expand All @@ -47,7 +47,8 @@ export async function createServer(root = process.cwd(), hmrPort) {
hmr: {
port: hmrPort
}
}
},
appType: 'custom'
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
Expand Down
5 changes: 3 additions & 2 deletions playground/ssr-pug/server.js
Expand Up @@ -31,7 +31,7 @@ export async function createServer(root = process.cwd(), hmrPort) {
root,
logLevel: isTest ? 'error' : 'info',
server: {
middlewareMode: 'ssr',
middlewareMode: true,
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
Expand All @@ -41,7 +41,8 @@ export async function createServer(root = process.cwd(), hmrPort) {
hmr: {
port: hmrPort
}
}
},
appType: 'custom'
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
Expand Down
5 changes: 3 additions & 2 deletions playground/ssr-react/server.js
Expand Up @@ -33,7 +33,7 @@ export async function createServer(
root,
logLevel: isTest ? 'error' : 'info',
server: {
middlewareMode: 'ssr',
middlewareMode: true,
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
Expand All @@ -43,7 +43,8 @@ export async function createServer(
hmr: {
port: hmrPort
}
}
},
appType: 'custom'
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
Expand Down
5 changes: 3 additions & 2 deletions playground/ssr-vue/server.js
Expand Up @@ -37,7 +37,7 @@ export async function createServer(
root,
logLevel: isTest ? 'error' : 'info',
server: {
middlewareMode: 'ssr',
middlewareMode: true,
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
Expand All @@ -47,7 +47,8 @@ export async function createServer(
hmr: {
port: hmrPort
}
}
},
appType: 'custom'
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
Expand Down