-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
41 lines (33 loc) · 1.15 KB
/
server.js
File metadata and controls
41 lines (33 loc) · 1.15 KB
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 { readFileSync } from "fs";
import exportss from "express";
import { join } from "path";
import { createServer as createViteServer } from "vite";
async function dataServer() {
const POST = 3000;
const app = exportss();
// 获取vite中间键并注册到app下
// 如果用vite自己的html逻辑就可以使用html
const vite = await createViteServer({
server: {
middlewareMode: "ssr"
},
});
app.use(vite.middlewares);
app.use("*", async (req, res) => {
// 触发请求执行
// 读取index.html
let template = readFileSync(join(__dirname, "index.html"), 'utf-8');
template = await vite.transformIndexHtml(req.originalUrl, template)
// 获取页面真实数据--由前段数据产出
const { render } = await vite.ssrLoadModule("/src/entry-server.js");
const appHtml = await render();
// 把读取到的数据替换
const html = template.replace(`<!--app-html-->`, appHtml);
// 返回完整数据
res.send(html);
})
app.listen(POST, () => {
// console.log('渲染成功');
})
}
dataServer();