安装依赖
npm install os
在 vue.config.js 配置文件中配置
-
增加一个函数用于获取本机内网 IP
const os = require('os'); function getNetworkIp() { // 打开的 host let needHost = ''; try { // 获得网络接口列表 let network = os.networkInterfaces(); 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; }
-
chainWebpack
函数中增加配置config.plugin('define').tap((args) => { const ip = getNetworkIp(); args[0]['process.env'].BASE_IP = `"${ip}"`; return args; });
获取使用
启动项目之后就可以从 process.env
的相应变量中获取到本机 IP 了
console.log('IPv4', process.env.BASE_IP)