You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.5 KiB

4 years ago
  1. 'use strict';
  2. const { createReadStream } = require('fs');
  3. const { join } = require('path');
  4. const clientBasePath = join(__dirname, '..', '..', 'client');
  5. function routes(app, middleware, options) {
  6. app.get('/__webpack_dev_server__/live.bundle.js', (req, res) => {
  7. res.setHeader('Content-Type', 'application/javascript');
  8. createReadStream(join(clientBasePath, 'live.bundle.js')).pipe(res);
  9. });
  10. app.get('/__webpack_dev_server__/sockjs.bundle.js', (req, res) => {
  11. res.setHeader('Content-Type', 'application/javascript');
  12. createReadStream(join(clientBasePath, 'sockjs.bundle.js')).pipe(res);
  13. });
  14. app.get('/webpack-dev-server.js', (req, res) => {
  15. res.setHeader('Content-Type', 'application/javascript');
  16. createReadStream(join(clientBasePath, 'index.bundle.js')).pipe(res);
  17. });
  18. app.get('/webpack-dev-server/*', (req, res) => {
  19. res.setHeader('Content-Type', 'text/html');
  20. createReadStream(join(clientBasePath, 'live.html')).pipe(res);
  21. });
  22. app.get('/webpack-dev-server', (req, res) => {
  23. res.setHeader('Content-Type', 'text/html');
  24. res.write(
  25. '<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>'
  26. );
  27. const outputPath = middleware.getFilenameFromUrl(options.publicPath || '/');
  28. const filesystem = middleware.fileSystem;
  29. writeDirectory(options.publicPath || '/', outputPath);
  30. res.end('</body></html>');
  31. function writeDirectory(baseUrl, basePath) {
  32. const content = filesystem.readdirSync(basePath);
  33. res.write('<ul>');
  34. content.forEach((item) => {
  35. const p = `${basePath}/${item}`;
  36. if (filesystem.statSync(p).isFile()) {
  37. res.write(`<li><a href="${baseUrl + item}">${item}</a></li>`);
  38. if (/\.js$/.test(item)) {
  39. const html = item.substr(0, item.length - 3);
  40. const containerHref = baseUrl + html;
  41. const magicHtmlHref =
  42. baseUrl.replace(
  43. // eslint-disable-next-line
  44. /(^(https?:\/\/[^\/]+)?\/)/,
  45. '$1webpack-dev-server/'
  46. ) + html;
  47. res.write(
  48. `<li><a href="${containerHref}">${html}</a>` +
  49. ` (magic html for ${item}) (<a href="${magicHtmlHref}">webpack-dev-server</a>)` +
  50. `</li>`
  51. );
  52. }
  53. } else {
  54. res.write(`<li>${item}<br>`);
  55. writeDirectory(`${baseUrl + item}/`, p);
  56. res.write('</li>');
  57. }
  58. });
  59. res.write('</ul>');
  60. }
  61. });
  62. }
  63. module.exports = routes;