proxy.ts 952 B

123456789101112131415161718192021222324252627282930313233343536
  1. import type { ProxyOptions } from 'vite';
  2. import { createServiceConfig } from '../../src/utils/service';
  3. /**
  4. * Set http proxy
  5. *
  6. * @param env - The current env
  7. * @param isDev - Is development environment
  8. */
  9. export function createViteProxy(env: Env.ImportMeta, isDev: boolean) {
  10. const isEnableHttpProxy = isDev && env.VITE_HTTP_PROXY === 'Y';
  11. if (!isEnableHttpProxy) return undefined;
  12. const { baseURL, proxyPattern, other } = createServiceConfig(env);
  13. const proxy: Record<string, ProxyOptions> = createProxyItem({ baseURL, proxyPattern });
  14. other.forEach(item => {
  15. Object.assign(proxy, createProxyItem(item));
  16. });
  17. return proxy;
  18. }
  19. function createProxyItem(item: App.Service.ServiceConfigItem) {
  20. const proxy: Record<string, ProxyOptions> = {};
  21. proxy[item.proxyPattern] = {
  22. target: item.baseURL,
  23. changeOrigin: true,
  24. rewrite: path => path.replace(new RegExp(`^${item.proxyPattern}`), '')
  25. };
  26. return proxy;
  27. }