Skip to content

Commit

Permalink
feat: connect to actual vite server port for websocket
Browse files Browse the repository at this point in the history
Allows assets to be served under a different port
close #452, close #460
  • Loading branch information
yyx990803 committed Jul 2, 2020
1 parent 0179c47 commit b6e91e0
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
3 changes: 2 additions & 1 deletion src/client/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// replaced by serverPluginHmr when served
declare const __SW_ENABLED__: boolean
declare const __PORT__: number

// This file runs in the browser.
import { HMRRuntime } from 'vue'
Expand Down Expand Up @@ -52,7 +53,7 @@ console.log('[vite] connecting...')
declare var __VUE_HMR_RUNTIME__: HMRRuntime

const socketProtocol = location.protocol === 'https:' ? 'wss' : 'ws'
const socketUrl = `${socketProtocol}://${location.host}`
const socketUrl = `${socketProtocol}://${location.hostname}:${__PORT__}`
const socket = new WebSocket(socketUrl, 'vite-hmr')

function warnFailedFetch(err: Error, path: string | string[]) {
Expand Down
11 changes: 8 additions & 3 deletions src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export interface ServerPluginContext {
watcher: HMRWatcher
resolver: InternalResolver
config: ServerConfig & { __path?: string }
port: number
}

export interface State extends DefaultState {}
Expand Down Expand Up @@ -71,7 +72,10 @@ export function createServer(config: ServerConfig): Server {
server,
watcher,
resolver,
config
config,
// port is exposed on the context for hmr client connection
// in case the files are served under a different port
port: config.port || 3000
}

// attach server context to koa context
Expand Down Expand Up @@ -109,11 +113,12 @@ export function createServer(config: ServerConfig): Server {
resolvedPlugins.forEach((m) => m && m(context))

const listen = server.listen.bind(server)
server.listen = (async (...args: any[]) => {
server.listen = (async (port: number, ...args: any[]) => {
if (optimizeDeps.auto !== false) {
await require('../optimizer').optimizeDeps(config)
}
return listen(...args)
context.port = port
return listen(port, ...args)
}) as any

return server
Expand Down
2 changes: 1 addition & 1 deletion src/node/server/serverPluginHmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export const hmrPlugin: ServerPlugin = ({
if (ctx.path === hmrClientPublicPath) {
ctx.type = 'js'
ctx.status = 200
ctx.body = hmrClient
ctx.body = hmrClient.replace(`__PORT__`, ctx.port.toString())
} else {
if (ctx.query.t) {
latestVersionsMap.set(ctx.path, ctx.query.t)
Expand Down

0 comments on commit b6e91e0

Please sign in to comment.