diff --git a/lib/Server.js b/lib/Server.js index 6e208128f6..424f60038e 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -4,6 +4,7 @@ const os = require("os"); const path = require("path"); const url = require("url"); const util = require("util"); +const readline = require("readline"); const fs = require("graceful-fs"); const ipaddr = require("ipaddr.js"); const { validate } = require("schema-utils"); @@ -309,6 +310,24 @@ function useFn(route, fn) { const DEFAULT_ALLOWED_PROTOCOLS = /^(file|.+-extension):/i; +/** + * @param {(host: string) => string} prettyPrintURL + */ +function setupKeypressLogger(prettyPrintURL) { + readline.emitKeypressEvents(process.stdin); + if (process.stdin.isTTY) { + process.stdin.setRawMode(true); + process.stdin.on("keypress", (str, key) => { + if (key.name === "u") { + console.log(`🔗 Dev Server: ${prettyPrintURL("localhost")}`); + } else if (key.name === "q" || (key.ctrl && key.name === "c")) { + process.exit(); + } + }); + console.log("🔑 Press [u] to show Dev Server URL, [q] to quit"); + } +} + /** * @typedef {Object} BasicApplication * @property {typeof useFn} use @@ -2917,6 +2936,11 @@ class Server { const prettyPrintURL = (newHostname) => url.format({ protocol, hostname: newHostname, port, pathname: "/" }); + // @ts-expect-error: we just added this option, TS types need updating + if (this.options.printUrlOnKeypress) { + setupKeypressLogger(prettyPrintURL); + } + let host; let localhost; let loopbackIPv4; diff --git a/lib/options.json b/lib/options.json index f5fa540624..ffe6664566 100644 --- a/lib/options.json +++ b/lib/options.json @@ -495,6 +495,11 @@ "description": "Allows to specify a port to use.", "link": "https://webpack.js.org/configuration/dev-server/#devserverport" }, + "PrintUrlOnKeypress": { + "type": "boolean", + "default": false, + "description": "Only print the Dev Server URL when the user presses 'u' in the terminal." + }, "Proxy": { "type": "array", "items": { @@ -976,6 +981,9 @@ "compress": { "$ref": "#/definitions/Compress" }, + "printUrlOnKeypress": { + "$ref": "#/definitions/PrintUrlOnKeypress" + }, "devMiddleware": { "$ref": "#/definitions/DevMiddleware" }, diff --git a/types/lib/Server.d.ts b/types/lib/Server.d.ts index a8e54e2df8..f1d1673a44 100644 --- a/types/lib/Server.d.ts +++ b/types/lib/Server.d.ts @@ -575,6 +575,11 @@ declare class Server< description: string; link: string; }; + PrintUrlOnKeypress: { + type: string; + default: boolean; + description: string; + }; Proxy: { type: string; items: { @@ -1066,6 +1071,9 @@ declare class Server< compress: { $ref: string; }; + printUrlOnKeypress: { + $ref: string; + }; devMiddleware: { $ref: string; };