Skip to content

Commit

Permalink
fix: call buildStart only once when using next port (#12624)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Mar 28, 2023
1 parent 0f9ad68 commit e10c6bd
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -669,20 +669,36 @@ export async function createServer(
depsOptimizer.server = server
}

// httpServer.listen can be called multiple times
// when port when using next port number
// this code is to avoid calling buildStart multiple times
let initingServer: Promise<void> | undefined
let serverInited = false
const initServer = async () => {
if (serverInited) return
if (initingServer) return initingServer

initingServer = (async function () {
await container.buildStart({})
initingServer = undefined
serverInited = true
})()
}

if (!middlewareMode && httpServer) {
// overwrite listen to init optimizer before server start
const listen = httpServer.listen.bind(httpServer)
httpServer.listen = (async (port: number, ...args: any[]) => {
try {
await container.buildStart({})
await initServer()
} catch (e) {
httpServer.emit('error', e)
return
}
return listen(port, ...args)
}) as any
} else {
await container.buildStart({})
await initServer()
}

return server
Expand Down

0 comments on commit e10c6bd

Please sign in to comment.