layui/package/document-layer/entry-server.ts

53 lines
1.6 KiB
TypeScript
Raw Normal View History

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
2022-01-04 10:12:13 +00:00
import { createApp } from "./main";
import { renderToString } from "@vue/server-renderer";
2021-09-26 22:09:33 +00:00
export async function render(url, manifest): Promise<string[]> {
2022-01-04 10:12:13 +00:00
const { app, router } = createApp();
2021-09-26 22:09:33 +00:00
// set the router to the desired URL before rendering
2022-01-04 10:12:13 +00:00
router.push(url);
await router.isReady();
2021-09-26 22:09:33 +00:00
// passing SSR context object which will be available via useSSRContext()
2022-01-04 10:12:13 +00:00
// @vitejs/plugin-vue injects code into a component's step() that registers
2021-09-26 22:09:33 +00:00
// itself on ctx.modules. After the render, ctx.modules would contain all the
// components that have been instantiated during this render call.
2022-01-04 10:12:13 +00:00
const ctx = {};
const html = await renderToString(app, ctx);
2021-09-26 22:09:33 +00:00
// the SSR manifest generated by Vite contains module -> chunk/asset mapping
// which we can then use to determine what files need to be preloaded for this
// request.
2022-01-04 10:12:13 +00:00
const preloadLinks = renderPreloadLinks(ctx.modules, manifest);
return [html, preloadLinks];
2021-09-26 22:09:33 +00:00
}
function renderPreloadLinks(modules, manifest) {
2022-01-04 10:12:13 +00:00
let links = "";
const seen = new Set();
2021-09-26 22:09:33 +00:00
modules.forEach((id) => {
2022-01-04 10:12:13 +00:00
const files = manifest[id];
2021-09-26 22:09:33 +00:00
if (files) {
files.forEach((file) => {
if (!seen.has(file)) {
2022-01-04 10:12:13 +00:00
seen.add(file);
links += renderPreloadLink(file);
2021-09-26 22:09:33 +00:00
}
2022-01-04 10:12:13 +00:00
});
2021-09-26 22:09:33 +00:00
}
2022-01-04 10:12:13 +00:00
});
return links;
2021-09-26 22:09:33 +00:00
}
function renderPreloadLink(file) {
2022-01-04 10:12:13 +00:00
if (file.endsWith(".js")) {
return `<link rel="modulepreload" crossorigin href="${file}">`;
} else if (file.endsWith(".css")) {
return `<link rel="stylesheet" href="${file}">`;
2021-09-26 22:09:33 +00:00
} else {
2022-01-04 10:12:13 +00:00
return "";
2021-09-26 22:09:33 +00:00
}
}