Guard Vite API proxy setup behind VUE_APP_API_URL and reuse it in preview

Co-Authored-By: Codex <codex@openai.com>
This commit is contained in:
2026-03-08 19:04:13 +08:00
parent a8cd590a11
commit 90cc6689c8

View File

@@ -14,8 +14,31 @@ import { fileURLToPath, URL } from "node:url";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
/**
* Builds Vite proxy configuration when backend target is available.
* @param {Record<string, string>} env - Loaded environment variables.
* @returns {Record<string, object>|undefined} Proxy config, or undefined when no target is configured.
*/
function createApiProxy(env) {
if (!env.VUE_APP_API_URL) {
console.warn(
"[vite] VUE_APP_API_URL is not set; /api proxy is disabled for this run.",
);
return undefined;
}
return {
"/api": {
target: env.VUE_APP_API_URL,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ""),
},
};
}
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd());
const proxy = createApiProxy(env);
return {
cacheDir: env.VITE_CACHE_DIR || undefined,
@@ -31,13 +54,12 @@ export default defineConfig(({ mode }) => {
server: {
host: "localhost",
port: 58249,
proxy: {
"/api": {
target: env.VUE_APP_API_URL,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
proxy,
},
preview: {
host: "localhost",
port: 4173,
proxy,
},
optimizeDeps: {
include: ["vue", "vue-router", "pinia", "axios"],