before.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const fs = require('fs');
  2. const os = require('os');
  3. function getIPAdress(flag = false) {
  4.   const interfaces = os.networkInterfaces();
  5.   for (const devName in interfaces) {
  6.     const iface = interfaces[devName];
  7.     for (let i = 0; i < iface.length; i++) {
  8.       const alias = iface[i];
  9.       const isIPV4 = !flag;
  10.       if (isIPV4) {
  11.         if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
  12.           return alias.address;
  13.         }
  14.       } else if (alias.address !== '127.0.0.1' && !alias.internal) {
  15.         if (alias.family === 'IPv6') {
  16.           return alias.address;
  17.         }
  18.       }
  19.     }
  20.   }
  21. }
  22. const IPv4 = getIPAdress();
  23. const envFile = fs.readFileSync('.env.development', 'utf8');
  24. const envVars = envFile.split('\n').reduce((result, line) => {
  25.   const parts = line.split('=');
  26.   if (parts.length === 2) {
  27.     result[parts[0].trim()] = parts[1].trim();
  28.   }
  29.   return result;
  30. }, {});
  31. envVars.VUE_APP_BASE_URL = `http://${IPv4}:8081`;
  32. const newEnvFile = Object.keys(envVars)
  33.   .map(key => `${key}=${envVars[key]}`)
  34.   .join('\n');
  35. fs.writeFileSync('.env.development', newEnvFile);