(root = process.cwd(), hmrPort)
| 6 | const isTest = process.env.VITEST |
| 7 | |
| 8 | export async function createServer(root = process.cwd(), hmrPort) { |
| 9 | const resolve = (p) => path.resolve(import.meta.dirname, p) |
| 10 | |
| 11 | const app = express() |
| 12 | |
| 13 | /** |
| 14 | * @type {import('vite').ViteDevServer} |
| 15 | */ |
| 16 | const vite = await ( |
| 17 | await import('vite') |
| 18 | ).createServer({ |
| 19 | root, |
| 20 | logLevel: isTest ? 'error' : 'info', |
| 21 | server: { |
| 22 | middlewareMode: true, |
| 23 | hmr: { |
| 24 | port: hmrPort, |
| 25 | }, |
| 26 | }, |
| 27 | appType: 'custom', |
| 28 | }) |
| 29 | app.use(vite.middlewares) |
| 30 | |
| 31 | app.use('*all', async (req, res) => { |
| 32 | try { |
| 33 | let template = fs.readFileSync(resolve('index.html'), 'utf-8') |
| 34 | template = await vite.transformIndexHtml(req.originalUrl, template) |
| 35 | |
| 36 | // `main.js` imports dependencies that are yet to be discovered and optimized, aka "missing" deps. |
| 37 | // Loading `main.js` in SSR should not trigger optimizing the "missing" deps |
| 38 | const { name } = await vite.ssrLoadModule('./main.js') |
| 39 | |
| 40 | // Loading `main.js` in the client should trigger optimizing the "missing" deps |
| 41 | const appHtml = `<div id="app">${name}</div> |
| 42 | <script type='module'> |
| 43 | import { name } from './main.js' |
| 44 | document.getElementById('app').innerText = name |
| 45 | </script>` |
| 46 | |
| 47 | const html = template.replace(`<!--app-html-->`, appHtml) |
| 48 | |
| 49 | res.status(200).set({ 'Content-Type': 'text/html' }).end(html) |
| 50 | } catch (e) { |
| 51 | vite.ssrFixStacktrace(e) |
| 52 | console.log(e.stack) |
| 53 | res.status(500).end(e.stack) |
| 54 | } |
| 55 | }) |
| 56 | |
| 57 | return { app, vite } |
| 58 | } |
| 59 | |
| 60 | if (!isTest) { |
| 61 | createServer().then(({ app }) => |
no test coverage detected