vite.config.ts 2.38 KB
import { networkInterfaces } from "node:os";
import { defineConfig, loadEnv } from "vite";
import uni from "@dcloudio/vite-plugin-uni";

/** 取本机第一个非回环 IPv4,供真机/App 与电脑访问同一台后端 */
function firstLanIPv4(): string | undefined {
  const list = networkInterfaces();
  for (const key of Object.keys(list)) {
    const addrs = list[key];
    if (!addrs) {
      continue;
    }
    for (const a of addrs) {
      const v4 = a.family === "IPv4" || a.family === 4;
      if (v4 && !a.internal) {
        return a.address;
      }
    }
  }
  return undefined;
}

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "");
  const raw = (env.VITE_API_BASE_URL || "").trim();
  const define: Record<string, string> = {};
  const plat = process.env.UNI_PLATFORM || "";
  const isH5Like = plat === "h5" || plat === "web";

  /**
   * H5 浏览器开发:不要用 127.0.0.1→局域网 IP 替换(易导致本机浏览器连 192.168.x.x 挂起超时);
   * 改为空 base + 同源代理到本机 PHP。
   */
  if (mode === "development" && isH5Like) {
    const target = (env.VITE_H5_PROXY_TARGET || "http://127.0.0.1:9898").replace(/\/+$/, "");
    define["import.meta.env.VITE_API_BASE_URL"] = JSON.stringify("");
    define["import.meta.env.VITE_API_RELATIVE"] = JSON.stringify("1");
    return {
      plugins: [uni()],
      define,
      server: {
        proxy: {
          "/api": { target, changeOrigin: true },
          "/admin": { target, changeOrigin: true },
          "/uploads": { target, changeOrigin: true },
        },
      },
    };
  }

  if (mode === "development" && env.VITE_API_STAY_LOCAL !== "1" && raw) {
    try {
      const normalized = /^https?:\/\//i.test(raw) ? raw : `http://${raw}`;
      const u = new URL(normalized);
      const host = (u.hostname || "").toLowerCase();
      if (host === "127.0.0.1" || host === "localhost") {
        const explicitLan = (env.VITE_API_LAN_IP || "").trim();
        const lan = explicitLan || firstLanIPv4();
        if (lan) {
          const port = u.port || (u.protocol === "https:" ? "443" : "80");
          const base = `${u.protocol}//${lan}:${port}`;
          define["import.meta.env.VITE_API_BASE_URL"] = JSON.stringify(base);
        }
      }
    } catch {
      /* 保持 .env 原样 */
    }
  }

  return {
    plugins: [uni()],
    define,
  };
});