serve.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import express, { NextFunction, Request, Response } from "express";
  2. import { resolve } from "path";
  3. import { fileURLToPath } from "url";
  4. import webpackCfg from "../../webpack.config.js";
  5. /** HTTP port of the dev server */
  6. const devServerPort = 8710;
  7. /** Whether to log requests to the console */
  8. const enableLogging = false;
  9. /** Whether to make a bell sound (in some terminals) when the userscript is ready to be fetched */
  10. const ringBell = true;
  11. const app = express();
  12. app.use((_req, _res, next) => {
  13. enableLogging && process.stdout.write("*");
  14. next();
  15. });
  16. app.use((err: unknown, _req: Request, _res: Response, _next: NextFunction) => {
  17. if(typeof err === "string" || err instanceof Error)
  18. console.error("\x1b[31mError in dev server:\x1b[0m\n", err);
  19. });
  20. // serves everything from `webpack_config.output.path` (`dist/` by default)
  21. app.use(express.static(
  22. resolve(fileURLToPath(import.meta.url), "../../", webpackCfg.output.path),
  23. {
  24. etag: false,
  25. maxAge: 5_000,
  26. }
  27. ));
  28. app.listen(devServerPort, "0.0.0.0", () => {
  29. console.log(`The dev server is running.\nUserscript is served at \x1b[34m\x1b[4mhttp://localhost:${devServerPort}/${webpackCfg.output.filename}\x1b[0m`);
  30. if(enableLogging)
  31. process.stdout.write("\nRequests: ");
  32. else
  33. console.log("\x1b[2m(request logging is disabled)\x1b[0m");
  34. ringBell && process.stdout.write("\u0007");
  35. });