-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
43 lines (38 loc) · 1.25 KB
/
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
42
43
const fs = require("fs");
const Koa = require("koa");
const path = require("path");
const koaStatic = require("koa-static");
const app = new Koa();
const resolve = (file) => path.resolve(__dirname, file);
// 开放dist目录
app.use(koaStatic(resolve("./dist/client")));
// 第 2 步:获得一个createBundleRenderer
const { createBundleRenderer } = require("vue-server-renderer");
const bundle = require("./dist/server/vue-ssr-server-bundle.json");
const clientManifest = require("./dist/client/vue-ssr-client-manifest.json");
const renderer = createBundleRenderer(bundle, {
runInNewContext: false,
template: fs.readFileSync(resolve("./public/index.temp.html"), "utf-8"),
clientManifest: clientManifest,
});
function renderToString(context) {
return new Promise((resolve, reject) => {
renderer.renderToString(context, (err, html) => {
err ? reject(err) : resolve(html);
});
});
}
// 第 3 步:添加一个中间件来处理所有请求
app.use(async (ctx, next) => {
const context = {
title: "ssr test",
url: ctx.url,
};
// 将 context 数据渲染为 HTML
const html = await renderToString(context);
ctx.body = html;
});
const port = 3000;
app.listen(port, function() {
console.log(`server started at localhost:${port}`);
});