Home > Enterprise >  Change Vite proxy location automatically in dev vs prod builds?
Change Vite proxy location automatically in dev vs prod builds?

Time:03-20

In my single page application I'm developing I'm using Vite and in my vite.config.ts file I have the following proxy:

proxy: {
  '/v1': {
    target: 'https://127.0.0.1:8080',
    changeOrigin: true,
    secure: false
  }
}

Is there a way to change this target depending on whether it is in the production environment? Something like:

proxy: {
  '/v1': {
    target: isDev ? 'https://127.0.0.1:8080' : 'https://api.example.com',
    changeOrigin: isDev,
    secure: !isDev
  }
}

That is, in my local environment I want to develop against my local server, such that my fetch API calls like fetch("/v1/get-posts") get forwarded to https://127.0.0.1:8080/v1/get-posts, but in my production build (which I create via vite build), they will instead be forwarded to: https://api.example.com/v1/get-posts

Can this be done, and if so, how?

CodePudding user response:

The dev server and its proxy config aren't bundled into the build output, so your goal does not make much sense practically. However, you technically can run the dev server in production mode via the mode flag, so perhaps that's what you meant.

In that case, you can use a conditional config, where isDev would be mode === 'development':

// vite.config.js
import { defineConfig } from 'vite'
import { fileURLToPath } from 'url'
import vue from '@vitejs/plugin-vue'

const defaultConfig = {
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
}

export default defineConfig(({ command, mode }) => {
  if (command === 'serve') {
                       
  • Related