| 15 | ` |
| 16 | |
| 17 | export async function createServer(root = process.cwd(), hmrPort) { |
| 18 | const resolve = (p) => path.resolve(import.meta.dirname, p) |
| 19 | |
| 20 | const app = express() |
| 21 | |
| 22 | /** |
| 23 | * @type {import('vite').ViteDevServer} |
| 24 | */ |
| 25 | const vite = await ( |
| 26 | await import('vite') |
| 27 | ).createServer({ |
| 28 | root, |
| 29 | logLevel: isTest ? 'error' : 'info', |
| 30 | server: { |
| 31 | middlewareMode: true, |
| 32 | watch: { |
| 33 | // During tests we edit the files too fast and sometimes chokidar |
| 34 | // misses change events, so enforce polling for consistency |
| 35 | usePolling: true, |
| 36 | interval: 100, |
| 37 | }, |
| 38 | hmr: { |
| 39 | port: hmrPort, |
| 40 | }, |
| 41 | }, |
| 42 | appType: 'custom', |
| 43 | }) |
| 44 | // use vite's connect instance as middleware |
| 45 | app.use(vite.middlewares) |
| 46 | |
| 47 | app.use('*all', async (req, res) => { |
| 48 | try { |
| 49 | let [url] = req.originalUrl.split('?') |
| 50 | url = url.replace(/\.html$/, '.pug') |
| 51 | if (url.endsWith('/')) url += 'index.pug' |
| 52 | |
| 53 | const htmlLoc = resolve(`.${url}`) |
| 54 | let html = pug.renderFile(htmlLoc) |
| 55 | html = html.replace('</body>', `${DYNAMIC_SCRIPTS}</body>`) |
| 56 | html = await vite.transformIndexHtml(url, html) |
| 57 | |
| 58 | res.status(200).set({ 'Content-Type': 'text/html' }).end(html) |
| 59 | } catch (e) { |
| 60 | vite && vite.ssrFixStacktrace(e) |
| 61 | console.log(e.stack) |
| 62 | res.status(500).end(e.stack) |
| 63 | } |
| 64 | }) |
| 65 | |
| 66 | return { app, vite } |
| 67 | } |
| 68 | |
| 69 | if (!isTest) { |
| 70 | createServer().then(({ app }) => |