前端常用webpack构建项目,但是默认情况下都是 http://localhost:8080 ,那么如何使用电脑的ip地址自动构建呢?
引入address
cnpm i address --save-dev
vue.config.js 使用
const address = require('address');
const localhost = address.ip() || 'localhost';
module.exports = {
...
devServer: {
open: process.platform === "darwin",
disableHostCheck: false,
// ip地址
host: localhost,
port: 8880,
https: false,
hotOnly: false, // See https://github.com/vuejs/vue-cli/blob/dev/docs/cli-service.md#configuring-proxy
proxy: null // string | Object
// before: app => {}
},
...
}
按照上边配置便能解决问题了。
但是address包问什么能够解决问题,它又是怎么封装的呢?
学习address源码
大家是知道webpack是基于node的,这里的address不过是对node的os操作系统进行了封装。
os(操作系统)
os 模块提供了与操作系统相关的实用方法和属性。 使用方法如下:
const os = require('os');
address源码解析
这里主要用到了 os.networkInterfaces() 方法(最小边有效果图),然后对它进行封装成address。
var os = require('os');
var fs = require('fs');
var child = require('child_process');
...
...
...
/**
* Get all addresses.
*
* @param {String} [interfaceName] interface name, default is 'eth' on linux, 'en' on mac os.
* @param {Function(err, addr)} callback
* - {Object} addr {
* - {String} ip
* - {String} ipv6
* - {String} mac
* }
*/
function address(interfaceName, callback) {
if (typeof interfaceName === 'function') {
callback = interfaceName;
interfaceName = null;
}
var addr = {
ip: address.ip(interfaceName),
ipv6: address.ipv6(interfaceName),
mac: null
};
address.mac(interfaceName, function (err, mac) {
if (mac) {
addr.mac = mac;
}
callback(err, addr);
});
}
// 这是重点 这是重点 这是重点 这是重点
address.interface = function (family, name) {
var interfaces = os.networkInterfaces();
var noName = !name;
name = name || getInterfaceName();
family = family || 'IPv4';
for (var i = -1; i < 8; i++) {
var interfaceName = name + (i >= 0 ? i : ''); // support 'lo' and 'lo0'
var items = interfaces[interfaceName];
if (items) {
for (var j = 0; j < items.length; j++) {
var item = items[j];
if (item.family === family) {
return item;
}
}
}
}
if (noName) {
// filter 127.0.0.1, get the first ip
for (var k in interfaces) {
var items = interfaces[k];
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (item.family === family && item.address !== '127.0.0.1') {
return item;
}
}
}
}
return;
};
....
...
...
/**
* Get current machine IPv4
*
* @param {String} [interfaceName] interface name, default is 'eth' on linux, 'en' on mac os.
* @return {String} IP address
*/
address.ip = function (interfaceName) {
var item = address.interface('IPv4', interfaceName);
return item && item.address;
};
...
...
...
module.exports = address;
os.networkInterfaces()效果图
感兴趣的小伙伴可以戳这里看源码~