serve.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. enableLogging &&
  13. app.use((_req, _res, next) => {
  14. process.stdout.write("*");
  15. next();
  16. });
  17. app.use((err: unknown, _req: Request, _res: Response, _next: NextFunction) => {
  18. if(typeof err === "string" || err instanceof Error)
  19. console.error("\x1b[31mError in dev server:\x1b[0m\n", err);
  20. });
  21. // serves everything from `webpack_config.output.path` (`dist/` by default)
  22. app.use(express.static(
  23. resolve(fileURLToPath(import.meta.url), "../../", webpackCfg.output.path),
  24. {
  25. etag: false,
  26. maxAge: 5_000,
  27. }
  28. ));
  29. app.listen(devServerPort, "0.0.0.0", () => {
  30. console.log(`The dev server is running.\nUserscript is served at \x1b[34m\x1b[4mhttp://localhost:${devServerPort}/${webpackCfg.output.filename}\x1b[0m`);
  31. if(enableLogging)
  32. process.stdout.write("\nRequests: ");
  33. else
  34. console.log("\x1b[2m(request logging is disabled)\x1b[0m");
  35. ringBell && process.stdout.write("\u0007");
  36. });