serveStatic.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. import { STATIC_SERVED_FILE_SUFFIX, CONTENT_TYPE_MAP } from '../../constant';
  2. import path from 'path';
  3. import { PluginOption, ViteDevServer } from 'vite';
  4. import fs from 'node:fs';
  5. /**
  6. * Plugin to serve static assets (placed in /public) in case to import them directly
  7. *
  8. * @link https://github.com/vitejs/vite/discussions/10356
  9. */
  10. export function configServerPlugin(): PluginOption {
  11. return {
  12. apply: 'serve',
  13. configureServer(server: ViteDevServer) {
  14. return () => {
  15. server.middlewares.use(async (req, res, next) => {
  16. STATIC_SERVED_FILE_SUFFIX.forEach((suffix) => {
  17. if (req.originalUrl?.includes(suffix)) {
  18. res.setHeader('Content-Type', CONTENT_TYPE_MAP.get(suffix) || 'application/application');
  19. res.writeHead(200);
  20. const [url] = (req.originalUrl || '')?.split('?');
  21. res.write(fs.readFileSync(path.join(__dirname, `../../../public/${url}`)));
  22. res.end();
  23. }
  24. next();
  25. });
  26. });
  27. };
  28. },
  29. name: 'serve-static',
  30. };
  31. }