-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
41 lines (34 loc) · 1015 Bytes
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import express from 'express';
import vite from 'vite';
import { resolve } from 'path';
import { cwd } from 'process';
import { readFile } from 'fs/promises';
async function server() {
const app = express();
/** @type {vite.ViteDevServer} */
const viteInstance = await vite.createServer({
// @ts-ignore
ssr: {
noExternal: ['cookie']
},
plugins: [],
server: { middlewareMode: true }
});
app.use(viteInstance.middlewares);
app.use('*', async (req, res) => {
const url = req.originalUrl;
try {
let template = await readFile(resolve(cwd(), 'index.html'), 'utf-8');
template = await viteInstance.transformIndexHtml(url, template);
const { default: app } = await viteInstance.ssrLoadModule('/src/app.js');
const html = template.replace('<!--ssr-outlet-->', app);
res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
} catch (e) {
viteInstance.ssrFixStacktrace(e);
console.error(e);
res.status(500).end(e.message);
}
});
app.listen(3000);
}
server();