UNPKG

1.25 kBJavaScriptView Raw
1const address = require('address');
2const chalk = require('chalk');
3
4function isPrivateIp(ip) {
5 // Check if the address is a private ip
6 // https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
7 return /^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(ip);
8}
9
10function getDevServerUrls(config) {
11 const devServer = config.devServer || {};
12 const host = devServer.host;
13 const port = devServer.port;
14 const protocol = devServer.https ? 'https' : 'http';
15
16 const localIp = devServer.wwwHost || 'localhost';
17 const localUrl = chalk.cyan(`${protocol}://${localIp}:${chalk.bold(port)}`);
18
19 let networkUrl;
20 try {
21 const networkIp = address.ip();
22 if (networkIp) {
23 // Check if the address is a private ip
24 // https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
25 if (isPrivateIp(networkIp)) {
26 // Address is private, format it for later use
27 networkUrl = chalk.cyan(`${protocol}://${networkIp}:${chalk.bold(port)}`);
28 }
29 }
30 }
31 catch (e) {
32 // Ignore
33 console.error(e);
34 }
35
36 if (!networkUrl || ['localhost', '127.0.0.1'].includes(host)) {
37 networkUrl = chalk.gray('unavailable');
38 }
39
40 return {
41 local: localUrl,
42 network: networkUrl,
43 };
44}
45
46module.exports = getDevServerUrls;