1.步骤条封装

This commit is contained in:
dingyongya
2022-01-04 18:12:13 +08:00
parent af5a0e0cc9
commit acef2f91b0
11 changed files with 1236 additions and 422 deletions

View File

@@ -1,52 +1,52 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
import { createApp } from './main'
import { renderToString } from '@vue/server-renderer'
import { createApp } from "./main";
import { renderToString } from "@vue/server-renderer";
export async function render(url, manifest): Promise<string[]> {
const { app, router } = createApp()
const { app, router } = createApp();
// set the router to the desired URL before rendering
router.push(url)
await router.isReady()
router.push(url);
await router.isReady();
// passing SSR context object which will be available via useSSRContext()
// @vitejs/plugin-vue injects code into a component's setup() that registers
// @vitejs/plugin-vue injects code into a component's step() that registers
// itself on ctx.modules. After the render, ctx.modules would contain all the
// components that have been instantiated during this render call.
const ctx = {}
const html = await renderToString(app, ctx)
const ctx = {};
const html = await renderToString(app, ctx);
// 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.
const preloadLinks = renderPreloadLinks(ctx.modules, manifest)
return [html, preloadLinks]
const preloadLinks = renderPreloadLinks(ctx.modules, manifest);
return [html, preloadLinks];
}
function renderPreloadLinks(modules, manifest) {
let links = ''
const seen = new Set()
let links = "";
const seen = new Set();
modules.forEach((id) => {
const files = manifest[id]
const files = manifest[id];
if (files) {
files.forEach((file) => {
if (!seen.has(file)) {
seen.add(file)
links += renderPreloadLink(file)
seen.add(file);
links += renderPreloadLink(file);
}
})
});
}
})
return links
});
return links;
}
function renderPreloadLink(file) {
if (file.endsWith('.js')) {
return `<link rel="modulepreload" crossorigin href="${file}">`
} else if (file.endsWith('.css')) {
return `<link rel="stylesheet" href="${file}">`
if (file.endsWith(".js")) {
return `<link rel="modulepreload" crossorigin href="${file}">`;
} else if (file.endsWith(".css")) {
return `<link rel="stylesheet" href="${file}">`;
} else {
return ''
return "";
}
}