Skip to content

Commit 66553d2

Browse files
committed
feat: find free port if port is not specified
1 parent b70602c commit 66553d2

File tree

1 file changed

+34
-15
lines changed

1 file changed

+34
-15
lines changed

lib/Server.js

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ const getCompilerConfigArray = require('./utils/getCompilerConfigArray');
3030
const getStatsOption = require('./utils/getStatsOption');
3131
const getColorsOption = require('./utils/getColorsOption');
3232
const setupExitSignals = require('./utils/setupExitSignals');
33+
const findPort = require('./utils/findPort');
3334
const schema = require('./options.json');
3435

3536
if (!process.env.WEBPACK_DEV_SERVER) {
@@ -598,26 +599,44 @@ class Server {
598599

599600
listen(port, hostname, fn) {
600601
this.hostname = hostname;
602+
if (typeof port !== 'undefined' && port !== this.options.port) {
603+
this.logger.warn(
604+
'The port specified in options and the port passed as an argument is different.'
605+
);
606+
}
601607

602-
return this.listeningApp.listen(port, hostname, (err) => {
603-
if (this.options.hot || this.options.liveReload) {
604-
this.createSocketServer();
605-
}
608+
return (
609+
findPort(port || this.options.port)
610+
// eslint-disable-next-line no-shadow
611+
.then((port) => {
612+
this.port = port;
606613

607-
if (this.options.bonjour) {
608-
runBonjour(this.options);
609-
}
614+
return this.listeningApp.listen(port, hostname, (err) => {
615+
if (this.options.hot || this.options.liveReload) {
616+
this.createSocketServer();
617+
}
610618

611-
this.showStatus();
619+
if (this.options.bonjour) {
620+
runBonjour(this.options);
621+
}
612622

613-
if (fn) {
614-
fn.call(this.listeningApp, err);
615-
}
623+
this.showStatus();
616624

617-
if (typeof this.options.onListening === 'function') {
618-
this.options.onListening(this);
619-
}
620-
});
625+
if (fn) {
626+
fn.call(this.listeningApp, err);
627+
}
628+
629+
if (typeof this.options.onListening === 'function') {
630+
this.options.onListening(this);
631+
}
632+
});
633+
})
634+
.catch((err) => {
635+
if (fn) {
636+
fn.call(this.listeningApp, err);
637+
}
638+
})
639+
);
621640
}
622641

623642
close(cb) {

0 commit comments

Comments
 (0)