serve.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import express, { NextFunction, Request, Response } from "express";
  2. import { resolve } from "path";
  3. import { fileURLToPath } from "url";
  4. import { output as webpackCfgOutput } from "../../webpack.config.js";
  5. import "dotenv/config";
  6. const envPort = Number(process.env.DEV_SERVER_PORT);
  7. /** HTTP port of the dev server */
  8. const devServerPort = isNaN(envPort) || envPort === 0 ? 8710 : envPort;
  9. /** Whether to log requests to the console */
  10. const enableLogging = false;
  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. app.use((_req, res, next) => {
  22. res.setHeader("Cache-Control", "no-store");
  23. next();
  24. });
  25. // serves everything from `webpackConfig.output.path` (`dist/` by default)
  26. app.use(express.static(
  27. resolve(fileURLToPath(import.meta.url), "../../", webpackCfgOutput.path)
  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}/${webpackCfgOutput.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. });