diff --git a/bin/utils.js b/bin/utils.js index 21873a1509..a59356b1b2 100644 --- a/bin/utils.js +++ b/bin/utils.js @@ -7,7 +7,6 @@ array-bracket-spacing, space-before-function-paren */ -const open = require('opn'); const colors = { info (useColor, msg) { @@ -70,22 +69,6 @@ function status (uri, options, log, useColor) { 'Broadcasting "http" with subtype of "webpack" via ZeroConf DNS (Bonjour)' ); } - - if (options.open) { - let openOptions = {}; - let openMessage = 'Unable to open browser'; - - if (typeof options.open === 'string') { - openOptions = { app: options.open }; - openMessage += `: ${options.open}`; - } - - open(uri + (options.openPage || ''), openOptions).catch(() => { - log.warn( - `${openMessage}. If you are running in a headless environment, please do not use the --open flag` - ); - }); - } } function bonjour (options) { diff --git a/examples/api/simple/server.js b/examples/api/simple/server.js index 3e148e047b..4ee34c7d2e 100644 --- a/examples/api/simple/server.js +++ b/examples/api/simple/server.js @@ -8,7 +8,8 @@ const compiler = Webpack(webpackConfig); const devServerOptions = Object.assign({}, webpackConfig.devServer, { stats: { colors: true - } + }, + open: true }); const server = new WebpackDevServer(compiler, devServerOptions); diff --git a/lib/Server.js b/lib/Server.js index 4a23f7cf79..b124bcd80d 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -27,6 +27,9 @@ const killable = require('killable'); const del = require('del'); const chokidar = require('chokidar'); +const open = require('opn'); +const createDomain = require('./utils/createDomain'); + const express = require('express'); const compress = require('compression'); @@ -77,6 +80,22 @@ const STATS = { errorDetails: false }; +function openBrowser(uri, options, log) { + let openOptions = {}; + let openMessage = 'Unable to open browser'; + + if (typeof options.open === 'string') { + openOptions = { app: options.open }; + openMessage += `: ${options.open}`; + } + + open(uri + (options.openPage || ''), openOptions).catch(() => { + log.warn( + `${openMessage}. If you are running in a headless environment, please do not use the --open flag` + ); + }); +} + function Server (compiler, options = {}, _log) { this.log = _log || createLogger(options); @@ -622,6 +641,8 @@ function Server (compiler, options = {}, _log) { this.listeningApp = http.createServer(app); } + this.options = options; + killable(this.listeningApp); // Proxy websockets without the initial http request @@ -804,6 +825,12 @@ Server.prototype.listen = function (port, hostname, fn) { if (fn) { fn.call(this.listeningApp, err); } + + if (this.options.open) { + const suffix = (this.options.inline !== false || this.options.lazy === true ? '/' : '/webpack-dev-server/'); + const uri = createDomain({ host: hostname, port }, this.listeningApp) + suffix; + openBrowser(uri, this.options, this.log); + } }); return returnValue;