-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (44 loc) · 1.26 KB
/
index.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
44
45
46
47
48
49
50
51
52
53
54
55
56
const path = require("path");
const fp = require("fastify-plugin");
const vite = require("vite");
const middie = require("@fastify/middie");
const ssrFactory = require("./ssr");
const { createServer } = vite;
// handle esm vs. commonjs mods
const returnRender = (m) => (m.default ? m.default.render : m.render);
async function ssr(fastify, opts, done) {
const { renderPath, readTemplate, populateTemplate, production, root } = {
...opts,
};
const template = readTemplate(root);
let render;
let renderMod;
let viteServer;
if (production) {
// eslint-disable-next-line global-require, import/no-dynamic-require
renderMod = require(path.resolve(renderPath));
render = returnRender(renderMod);
} else {
// dev server magic
viteServer = await createServer({
root,
logLevel: "info",
server: {
middlewareMode: "ssr",
},
});
await fastify.register(middie);
fastify.use(viteServer.middlewares);
renderMod = await viteServer.ssrLoadModule(path.resolve(renderPath));
render = returnRender(renderMod);
}
const ssrDecorator = await ssrFactory(
render,
template,
populateTemplate,
viteServer
);
fastify.decorateReply("ssr", ssrDecorator);
done();
}
module.exports = fp(ssr);