From 6f2aa1061738d871628270b2c6345242d2626192 Mon Sep 17 00:00:00 2001 From: underfin Date: Tue, 20 Oct 2020 11:55:47 +0800 Subject: [PATCH] refactor: replacement websocket url with `hmr` option --- src/node/config.ts | 14 ++++++++++++++ src/node/server/serverPluginClient.ts | 14 ++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/node/config.ts b/src/node/config.ts index 3ae445ef89cc57..6c9f9b2fa84231 100644 --- a/src/node/config.ts +++ b/src/node/config.ts @@ -166,7 +166,21 @@ export interface SharedConfig { env?: DotenvParseOutput } +export interface HmrConfig { + protocol?: string + hostname?: string + port?: number + path?: string +} + export interface ServerConfig extends SharedConfig { + /** + * Configure hmr websocket connection. + */ + hmr?: HmrConfig | boolean + /** + * Configure dev server hostname. + */ hostname?: string port?: number open?: boolean diff --git a/src/node/server/serverPluginClient.ts b/src/node/server/serverPluginClient.ts index 62afc4712c287b..6408c90558a603 100644 --- a/src/node/server/serverPluginClient.ts +++ b/src/node/server/serverPluginClient.ts @@ -25,8 +25,18 @@ export const clientPlugin: ServerPlugin = ({ app, config }) => { app.use(async (ctx, next) => { if (ctx.path === clientPublicPath) { const socketProtocol = ctx.protocol.toString() === 'https' ? 'wss' : 'ws' - const socketUrl = `${socketProtocol}://${ctx.host.toString()}` - + let socketUrl = `${socketProtocol}://${ctx.host.toString()}` + if (config.hmr && typeof config.hmr === 'object') { + // hmr option has highest priory + let { protocol, hostname, port, path } = config.hmr + protocol = protocol || socketProtocol + hostname = hostname || ctx.hostname + port = port || ctx.port + socketUrl = `${protocol}://${hostname}:${port}` + if (path) { + socketUrl = socketUrl + '/' + path + } + } ctx.type = 'js' ctx.status = 200 ctx.body = clientCode.replace(`__HOST__`, JSON.stringify(socketUrl))