|
| 1 | +import fs from 'node:fs' |
| 2 | +import path from 'node:path' |
| 3 | +import { fileURLToPath } from 'node:url' |
| 4 | +import express from 'express' |
| 5 | + |
| 6 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)) |
| 7 | + |
| 8 | +const isTest = process.env.VITEST |
| 9 | + |
| 10 | +export async function createServer( |
| 11 | + root = process.cwd(), |
| 12 | + isProd = process.env.NODE_ENV === 'production', |
| 13 | + hmrPort |
| 14 | +) { |
| 15 | + const resolve = (p) => path.resolve(__dirname, p) |
| 16 | + |
| 17 | + const indexProd = isProd |
| 18 | + ? fs.readFileSync(resolve('index.html'), 'utf-8') |
| 19 | + : '' |
| 20 | + |
| 21 | + const app = express() |
| 22 | + |
| 23 | + /** |
| 24 | + * @type {import('vite').ViteDevServer} |
| 25 | + */ |
| 26 | + let vite |
| 27 | + if (!isProd) { |
| 28 | + vite = await ( |
| 29 | + await import('vite') |
| 30 | + ).createServer({ |
| 31 | + root, |
| 32 | + logLevel: isTest ? 'error' : 'info', |
| 33 | + server: { |
| 34 | + middlewareMode: true, |
| 35 | + watch: { |
| 36 | + // During tests we edit the files too fast and sometimes chokidar |
| 37 | + // misses change events, so enforce polling for consistency |
| 38 | + usePolling: true, |
| 39 | + interval: 100 |
| 40 | + }, |
| 41 | + hmr: { |
| 42 | + port: hmrPort |
| 43 | + } |
| 44 | + }, |
| 45 | + appType: 'custom' |
| 46 | + }) |
| 47 | + app.use(vite.middlewares) |
| 48 | + } |
| 49 | + |
| 50 | + app.use('*', async (req, res) => { |
| 51 | + try { |
| 52 | + const url = req.originalUrl |
| 53 | + |
| 54 | + let template, render |
| 55 | + if (!isProd) { |
| 56 | + // always read fresh template in dev |
| 57 | + template = fs.readFileSync(resolve('index.html'), 'utf-8') |
| 58 | + template = await vite.transformIndexHtml(url, template) |
| 59 | + render = (await vite.ssrLoadModule('/src/entry-server.js')).render |
| 60 | + } else { |
| 61 | + template = indexProd |
| 62 | + // @ts-ignore |
| 63 | + render = (await import('./dist/entry-server.js')).render |
| 64 | + } |
| 65 | + |
| 66 | + const appHtml = await render(url) |
| 67 | + |
| 68 | + const html = template.replace(`<!--app-html-->`, appHtml) |
| 69 | + |
| 70 | + res.status(200).set({ 'Content-Type': 'text/html' }).end(html) |
| 71 | + } catch (e) { |
| 72 | + !isProd && vite.ssrFixStacktrace(e) |
| 73 | + console.log(e.stack) |
| 74 | + res.status(500).end(e.stack) |
| 75 | + } |
| 76 | + }) |
| 77 | + |
| 78 | + return { app, vite } |
| 79 | +} |
| 80 | + |
| 81 | +if (!isTest) { |
| 82 | + createServer().then(({ app }) => |
| 83 | + app.listen(5173, () => { |
| 84 | + console.log('http://localhost:5173') |
| 85 | + }) |
| 86 | + ) |
| 87 | +} |
0 commit comments