Sometimes there is a need to access the vue project via IP address on the LAN, so we document the method to get the local IP.

Installing dependencies

To get the IP, we need to use the os module, and we need to install the following dependencies.

1
npm install os

Modify the configuration

You need to modify the project configuration file vue.config.js.

  1. Add a function to get the local intranet IP.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const os = require('os');
function getNetworkIp() {
  // 打开的 host
  let needHost = '';
  try {
    // 获得网络接口列表
    let network = os.networkInterfaces();
    console.log(network);
    for (let dev in network) {
      let iface = network[dev];
      for (let i = 0; i < iface.length; i++) {
        let alias = iface[i];
        if (
          alias.family === 'IPv4' &&
          alias.address !== '127.0.0.1' &&
          !alias.internal
        ) {
          needHost = alias.address;
        }
      }
    }
  } catch (e) {
    needHost = 'http://localhost';
  }
  return needHost;
}
  1. Add configuration to the chainWebpack function.
1
2
3
4
5
config.plugin('define').tap((args) => {
  let ip = getNetworkIp();
  args[0]['process.env'].BASE_IP = `"http://${ip}:${port}"`;
  return args;
});

Use

After starting the project, you can get the local IP from the corresponding variable in process.env.

References