Skip to content

Commit

Permalink
feat(dev): proxy ws (vitejs#865)
Browse files Browse the repository at this point in the history
  • Loading branch information
underfin authored Sep 29, 2020
1 parent 2893a41 commit c3ef4f6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ import { ServerPlugin } from './server'
import { Resolver, supportedExts } from './resolver'
import { Transform, CustomBlockTransform } from './transform'
import { DepOptimizationOptions } from './optimizer'
import { IKoaProxiesOptions } from 'koa-proxies'
import { ServerOptions } from 'https'
import { lookupFile } from './utils'
import { Options as RollupTerserOptions } from 'rollup-plugin-terser'
import { ProxiesOptions } from './server/serverPluginProxy'

export type PreprocessLang = NonNullable<
SFCStyleCompileOptions['preprocessLang']
Expand Down Expand Up @@ -198,7 +198,7 @@ export interface ServerConfig extends SharedConfig {
* }
* ```
*/
proxy?: Record<string, string | IKoaProxiesOptions>
proxy?: Record<string, string | ProxiesOptions>
/**
* A plugin function that configures the dev server. Receives a server plugin
* context object just like the internal server plguins. Can also be an array
Expand Down
19 changes: 17 additions & 2 deletions src/node/server/serverPluginProxy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { ServerPlugin } from '.'
import { URL } from 'url'
import { IKoaProxiesOptions } from 'koa-proxies'

export const proxyPlugin: ServerPlugin = ({ app, config }) => {
export type ProxiesOptions = IKoaProxiesOptions & { ws: boolean }

export const proxyPlugin: ServerPlugin = ({ app, config, server }) => {
if (!config.proxy) {
return
}
Expand All @@ -12,8 +15,9 @@ export const proxyPlugin: ServerPlugin = ({ app, config }) => {
Object.keys(options).forEach((path) => {
let opts = options[path]
if (typeof opts === 'string') {
opts = { target: opts }
opts = { target: opts } as ProxiesOptions
}
if (opts.ws) return
opts.logs = (ctx, target) => {
debug(
`${ctx.req.method} ${(ctx.req as any).oldPath} proxy to -> ${new URL(
Expand All @@ -24,4 +28,15 @@ export const proxyPlugin: ServerPlugin = ({ app, config }) => {
}
app.use(proxy(path, opts))
})

server.on('upgrade', (req, socket, head) => {
if (req.headers['sec-websocket-protocol'] !== 'vite-hmr') {
for (const path in options) {
let opts = options[path]
if (typeof opts === 'object' && opts.ws) {
proxy.proxy.ws(req, socket, head, opts)
}
}
}
})
}

0 comments on commit c3ef4f6

Please sign in to comment.