import { STATIC_SERVED_FILE_SUFFIX, CONTENT_TYPE_MAP } from '../../constant'; import path from 'path'; import { PluginOption, ViteDevServer } from 'vite'; import fs from 'node:fs'; /** * Plugin to serve static assets (placed in /public) in case to import them directly * * @link https://github.com/vitejs/vite/discussions/10356 */ export function configServerPlugin(): PluginOption { return { apply: 'serve', configureServer(server: ViteDevServer) { return () => { server.middlewares.use(async (req, res, next) => { STATIC_SERVED_FILE_SUFFIX.forEach((suffix) => { if (req.originalUrl?.includes(suffix)) { res.setHeader('Content-Type', CONTENT_TYPE_MAP.get(suffix) || 'application/application'); res.writeHead(200); const [url] = (req.originalUrl || '')?.split('?'); res.write(fs.readFileSync(path.join(__dirname, `../../../public/${url}`))); res.end(); } next(); }); }); }; }, name: 'serve-static', }; }