|
| 1 | +import { createSSRApp } from "vue"; |
| 2 | +import { renderToString } from "vue/server-renderer"; |
| 3 | +import { RouterView, createMemoryHistory, createRouter } from "vue-router"; |
| 4 | + |
| 5 | +import { createHead, transformHtmlTemplate } from "unhead/server"; |
| 6 | + |
| 7 | +import { routes } from "./routes"; |
| 8 | + |
| 9 | +// @ts-ignore |
| 10 | +import clientEntry from "./entry-client.ts?assets=client"; |
| 11 | + |
| 12 | +async function handler(request: Request): Promise<Response> { |
| 13 | + const app = createSSRApp(RouterView); |
| 14 | + const router = createRouter({ history: createMemoryHistory(), routes }); |
| 15 | + app.use(router); |
| 16 | + |
| 17 | + const url = new URL(request.url); |
| 18 | + const href = url.href.slice(url.origin.length); |
| 19 | + |
| 20 | + await router.push(href); |
| 21 | + await router.isReady(); |
| 22 | + |
| 23 | + const assets = clientEntry.merge( |
| 24 | + ...(await Promise.all( |
| 25 | + router.currentRoute.value.matched |
| 26 | + .map((to) => to.meta.assets) |
| 27 | + .filter(Boolean) |
| 28 | + .map((fn) => fn!().then((m) => m.default)), |
| 29 | + )), |
| 30 | + ); |
| 31 | + |
| 32 | + const head = createHead(); |
| 33 | + |
| 34 | + head.push({ |
| 35 | + link: [ |
| 36 | + ...assets.css.map((attrs: any) => ({ rel: "stylesheet", ...attrs })), |
| 37 | + ...assets.js.map((attrs: any) => ({ rel: "modulepreload", ...attrs })), |
| 38 | + ], |
| 39 | + script: [{ type: "module", src: clientEntry.entry }], |
| 40 | + }); |
| 41 | + |
| 42 | + const renderedApp = await renderToString(app); |
| 43 | + |
| 44 | + const html = await transformHtmlTemplate(head, htmlTemplate(renderedApp)); |
| 45 | + |
| 46 | + return new Response(html, { |
| 47 | + headers: { "Content-Type": "text/html;charset=utf-8" }, |
| 48 | + }); |
| 49 | +} |
| 50 | + |
| 51 | +function htmlTemplate(body: string): string { |
| 52 | + return /* html */ `\<!DOCTYPE html> |
| 53 | +<html lang="en"> |
| 54 | +<head> |
| 55 | + <meta charset="UTF-8" /> |
| 56 | + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> |
| 57 | + <title>Vue Router Custom Framework</title> |
| 58 | +</head> |
| 59 | +<body> |
| 60 | + <div id="root">${body}</div> |
| 61 | +</body> |
| 62 | +</html>`; |
| 63 | +} |
| 64 | + |
| 65 | +export default { |
| 66 | + fetch: handler, |
| 67 | +}; |
0 commit comments