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:
@@ -14,8 +14,31 @@ import { fileURLToPath, URL } from "node:url";
|
|||||||
import { defineConfig, loadEnv } from "vite";
|
import { defineConfig, loadEnv } from "vite";
|
||||||
import vue from "@vitejs/plugin-vue";
|
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 }) => {
|
export default defineConfig(({ mode }) => {
|
||||||
const env = loadEnv(mode, process.cwd());
|
const env = loadEnv(mode, process.cwd());
|
||||||
|
const proxy = createApiProxy(env);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
cacheDir: env.VITE_CACHE_DIR || undefined,
|
cacheDir: env.VITE_CACHE_DIR || undefined,
|
||||||
@@ -31,13 +54,12 @@ export default defineConfig(({ mode }) => {
|
|||||||
server: {
|
server: {
|
||||||
host: "localhost",
|
host: "localhost",
|
||||||
port: 58249,
|
port: 58249,
|
||||||
proxy: {
|
proxy,
|
||||||
"/api": {
|
|
||||||
target: env.VUE_APP_API_URL,
|
|
||||||
changeOrigin: true,
|
|
||||||
rewrite: (path) => path.replace(/^\/api/, ""),
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
|
preview: {
|
||||||
|
host: "localhost",
|
||||||
|
port: 4173,
|
||||||
|
proxy,
|
||||||
},
|
},
|
||||||
optimizeDeps: {
|
optimizeDeps: {
|
||||||
include: ["vue", "vue-router", "pinia", "axios"],
|
include: ["vue", "vue-router", "pinia", "axios"],
|
||||||
|
|||||||
Reference in New Issue
Block a user