Skip to content

Commit

Permalink
feat(server): add strict-port option (#1453)
Browse files Browse the repository at this point in the history
  • Loading branch information
stafyniaksacha committed Jan 11, 2021
1 parent 4ca20f2 commit 0501084
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
6 changes: 6 additions & 0 deletions docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,12 @@ export default ({ command, mode }) => {

Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on.

### server.strictPort

- **Type:** `boolean`

Set to `true` to exit if port is already in use, instead of automatically try the next available port.

### server.https

- **Type:** `boolean | https.ServerOptions`
Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/node/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ cli
.option('--https', `[boolean] use TLS + HTTP/2`)
.option('--open [browser]', `[boolean | string] open browser on startup`)
.option('--cors', `[boolean] enable CORS`)
.option('--strict-port', `[boolean] exit if specified port is already in use`)
.option('-m, --mode <mode>', `[string] set env mode`)
.option(
'--force',
Expand Down
13 changes: 11 additions & 2 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ export interface ServerOptions {
* using an object.
*/
cors?: CorsOptions | boolean
/**
* If enabled, vite will exit if specified port is already in use
*/
strictPort?: boolean
}

/**
Expand Down Expand Up @@ -402,8 +406,13 @@ async function startServer(
return new Promise((resolve, reject) => {
const onError = (e: Error & { code?: string }) => {
if (e.code === 'EADDRINUSE') {
info(`Port ${port} is in use, trying another one...`)
httpServer.listen(++port)
if (options.strictPort) {
httpServer.removeListener('error', onError)
reject(new Error(`Port ${port} is already in use`))
} else {
info(`Port ${port} is in use, trying another one...`)
httpServer.listen(++port)
}
} else {
httpServer.removeListener('error', onError)
reject(e)
Expand Down

0 comments on commit 0501084

Please sign in to comment.