server.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * Copyright (c) 2013-Now https://jeesite.com All rights reserved.
  3. * No deletion without permission, or be held responsible to law.
  4. * @author ThinkGem
  5. */
  6. import type { ServerOptions, ProxyOptions } from 'vite';
  7. import { IncomingMessage } from 'node:http';
  8. type ProxyItem = [string, string, boolean];
  9. type ProxyList = ProxyItem[];
  10. type ProxyTargetList = Record<string, ProxyOptions>;
  11. const httpsRE = /^https:\/\//;
  12. export function createServerOptions(viteEnv: ViteEnv): ServerOptions {
  13. return {
  14. https: false as any,
  15. open: false,
  16. host: true,
  17. port: viteEnv.VITE_PORT,
  18. // Electron dev startup checks a fixed URL, so do not let Vite silently hop ports.
  19. strictPort: true,
  20. proxy: createProxy(viteEnv.VITE_PROXY),
  21. warmup: {
  22. clientFiles: ['./index.html', './src/{views,components}/*'],
  23. },
  24. };
  25. }
  26. /**
  27. * Used to parse the .env.development proxy configuration
  28. */
  29. export function createProxy(list: ProxyList = []) {
  30. const ret: ProxyTargetList = {};
  31. for (const [prefix, target, changeOrigin] of list) {
  32. const isHttps = httpsRE.test(target);
  33. // https://github.com/http-party/node-http-proxy#options
  34. ret[prefix] = {
  35. target: target,
  36. changeOrigin,
  37. ws: true,
  38. // https is require secure=false
  39. ...(isHttps ? { secure: false } : {}),
  40. rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
  41. bypass: (req: IncomingMessage) => {
  42. if (req.method === 'GET') {
  43. req['url'] = req['originalUrl'];
  44. }
  45. },
  46. };
  47. }
  48. return ret;
  49. }