本机电脑由于开启Hyper-V,所以默认得到的内网是虚拟网卡的IP,所以需要特殊的方法来得到内网IP
一、package.json
原代码
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
},
改为
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js --host 0.0.0.0",
},
二、webpack.dev.conf.js
添加代码(动态获取本地IP)—— 注:由于本机开启了Hyper-V所以需要特殊方法来获得内网IP
// 获取本地ip
function getNetWorkIp() {
// 打开host
let needHost = '';
try {
let network = os.networkInterfaces();
for (const dev in network) {
let iface = network[dev];
for (let i = 0; i < iface.length; i++) {
const alias = iface[i];
if (
alias.family === 'IPv4' &&
alias.address !== '127.0.0.1' &&
!alias.internal
) {
needHost = alias.address;
}
}
}
} catch (error) {
needHost = 'http://localhost';
}
return needHost
}
const IP = getNetWorkIp();
代码改动,原为
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
改为
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [
`App runing at: `,
`本地: http://${devWebpackConfig.devServer.host}:${port}`,
`内网: http://${IP}:${port}`,
],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
注:网上有其他的方法获得内网址IP,经尝试电脑开启Hyper-V状态下未得到想要的IP,得到的是以太网适配器 vEthernet (Default Switch)的IP
require('ip').address()
require('address').ip() 经测试,该方法需要特别安装address(npm i address -D)
前以两个命令得到的结果如下
该IP本地能访问,同WIFI下的其他终端不能访问
上面写的getNetWorkIp方法可以得到我想要的IP,结果如下
如上图IPv4地址即是想要结果。