proxy.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /**
  2. * Used to parse the .env.development proxy configuration
  3. */
  4. import type { ProxyOptions } from 'vite';
  5. type ProxyItem = [string, string];
  6. type ProxyList = ProxyItem[];
  7. type ProxyTargetList = Record<string, ProxyOptions & { rewrite: (path: string) => string }>;
  8. const httpsRE = /^https:\/\//;
  9. /**
  10. * Generate proxy
  11. * @param list
  12. */
  13. export function createProxy(list: ProxyList = []) {
  14. const ret: ProxyTargetList = {};
  15. for (const [prefix, target] of list) {
  16. const isHttps = httpsRE.test(target);
  17. // https://github.com/http-party/node-http-proxy#options
  18. ret[prefix] = {
  19. target: target,
  20. changeOrigin: true,
  21. ws: true,
  22. rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
  23. // https is require secure=false
  24. ...(isHttps ? { secure: false } : {}),
  25. // configure: (proxy, options) => {
  26. // proxy.on('proxyReq', (proxyReq, req, res) => {
  27. // console.log(`[Proxy] ${req.method} ${req.url}`);
  28. // });
  29. // proxy.on('proxyRes', (proxyRes, req, res) => {
  30. // console.log(`[Proxy] ${res.statusCode} ${req.method} ${req.url}`);
  31. // });
  32. // }
  33. };
  34. }
  35. return ret;
  36. }