Skip to content

Commit 5bee6bb

Browse files
benwiley4000SpaceK33z
authored andcommitted
CLI finds and uses 1st available port when none specified. (#685)
1 parent 46f19f9 commit 5bee6bb

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

bin/webpack-dev-server.js

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ var open = require("opn");
55
var fs = require("fs");
66
var net = require("net");
77
var url = require("url");
8+
var portfinder = require("portfinder");
89

910
// Local version replaces global one
1011
try {
@@ -46,6 +47,11 @@ var CONNECTION_GROUP = "Connection options:";
4647
var RESPONSE_GROUP = "Response options:";
4748
var BASIC_GROUP = "Basic options:";
4849

50+
// Taken out of yargs because we must know if
51+
// it wasn't given by the user, in which case
52+
// we should use portfinder.
53+
var DEFAULT_PORT = 8080;
54+
4955
yargs.options({
5056
"lazy": {
5157
type: "boolean",
@@ -143,7 +149,6 @@ yargs.options({
143149
},
144150
"port": {
145151
describe: "The port",
146-
default: 8080,
147152
group: CONNECTION_GROUP
148153
},
149154
"socket": {
@@ -190,9 +195,6 @@ function processOptions(wpOpt) {
190195
if(argv.public)
191196
options.public = argv.public;
192197

193-
if(argv.port !== 8080 || !options.port)
194-
options.port = argv.port;
195-
196198
if(argv.socket)
197199
options.socket = argv.socket;
198200

@@ -291,6 +293,25 @@ function processOptions(wpOpt) {
291293
if(argv["open"])
292294
options.open = true;
293295

296+
// Kind of weird, but ensures prior behavior isn't broken in cases
297+
// that wouldn't throw errors. E.g. both argv.port and options.port
298+
// were specified, but since argv.port is 8080, options.port will be
299+
// tried first instead.
300+
options.port = argv.port === DEFAULT_PORT ? (options.port || argv.port) : (argv.port || options.port);
301+
if(options.port) {
302+
startDevServer(wpOpt, options);
303+
return;
304+
}
305+
306+
portfinder.basePort = DEFAULT_PORT;
307+
portfinder.getPort(function(err, port) {
308+
if(err) throw err;
309+
options.port = port;
310+
startDevServer(wpOpt, options);
311+
});
312+
}
313+
314+
function startDevServer(wpOpt, options) {
294315
var protocol = options.https ? "https" : "http";
295316

296317
// the formatted domain (url without path) of the webpack server

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
"express": "^4.13.3",
1414
"http-proxy-middleware": "~0.17.1",
1515
"opn": "4.0.2",
16+
"portfinder": "^1.0.9",
1617
"serve-index": "^1.7.2",
1718
"sockjs": "0.3.18",
1819
"sockjs-client": "1.1.1",

0 commit comments

Comments
 (0)