vue本地运行项目,自动更新IP地址
一、编写一个js文件,命名为updateBaseUrl
const fs = require('fs-extra');
const path = require('path');
const os = require('os');
let currentIP = Object.values(os.networkInterfaces())
.flat(Infinity)
.find(item => {
return (
item.family === 'IPv4' && item.address !== '127.0.0.1' && !item.internal
);
})?.address;
/** 处理更新函数逻辑 */
const handleUpdate = async () => {
// 找到baseUrl的json文件
const targetFile = path.join(__dirname, '../../../public/baseUrl.json');//填写对应的文件地址
// 读取
const data = await fs.readJson(targetFile);
// 正则匹配出老URL
let oldIP = data.baseUrl.match(/\/\/(.*):/)[1];
// 用新的URL替换
data.baseUrl = data.baseUrl.replace(oldIP, currentIP);
// 写入新的JSON
fs.writeJson(targetFile, data, {
spaces: 2
});
};
handleUpdate();
二、package.json加上执行指令
"scripts": {
"serve": "npm run updateBaseUrl && vue-cli-service serve", //运行的时候执行指令
"test": "vue-cli-service serve --mode test",
"pro": "vue-cli-service serve --mode production",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"updateBaseUrl": "node ./src/node/updateBaseUrl"
},