proxy.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const http = require('http');
  2. const httpProxy = require('http-proxy');
  3. const proxy = httpProxy.createProxyServer({});
  4. const ports = {
  5. proxy: parseInt(process.env.npm_package_config_ports_proxy, 10),
  6. jekyll: parseInt(process.env.npm_package_config_ports_jekyll, 10),
  7. karma: parseInt(process.env.npm_package_config_ports_karma, 10),
  8. webpack: parseInt(process.env.npm_package_config_ports_webpack, 10),
  9. };
  10. const server = http.createServer((req, res) => {
  11. if (
  12. /\/\d+\.\d+\.\d+/.test(req.url) ||
  13. req.url.startsWith('/karma/base/dist')
  14. ) {
  15. const target = `http://localhost:${ports.webpack}/${req.url
  16. .split('/')
  17. .pop()}`;
  18. proxy.web(req, res, {
  19. ignorePath: true,
  20. target,
  21. });
  22. } else if (
  23. req.url.startsWith('/karma') ||
  24. req.url === '/assets/favicon.png'
  25. ) {
  26. proxy.web(req, res, { ignorePath: false, target: { port: ports.karma } });
  27. } else {
  28. proxy.web(req, res, { ignorePath: false, target: { port: ports.jekyll } });
  29. }
  30. });
  31. server.on('upgrade', (req, socket, head) => {
  32. proxy.ws(req, socket, head);
  33. });
  34. proxy.on('error', e => {
  35. console.error(e);
  36. });
  37. console.log('Proxy listening on ' + ports.proxy);
  38. server.listen(ports.proxy);