import { createApp } from './main'
import { renderToString } from 'vue/server-renderer'
export async function render(url: string,manifest:any) {
const { app, router, store } = createApp()
await router.push(url)
await router.isReady()
const matchedComponents = router.currentRoute.value.matched.flatMap(record =>Object.values(record.components))
//对所有匹配的路由组件调用`asyncData()
await Promise.all(matchedComponents.map((Component:any) =>{
if(Component.asyncData){
return Component.asyncData({
store,
route: router.currentRoute
})
}
}))
const context:any = {}
const appHtml = await renderToString(app,context)
const state = store.state
// preloadLinks 文件预加载
if(import.meta.env.PROD){
const preloadLinks = renderLinks(context.modules,manifest)
return { appHtml, state, preloadLinks }
}else{
return { appHtml, state }
}
}
//文件路径获取
function renderLinks(modules:any,manifest:any){
console.log(90,modules)
let links = ""
modules.forEach((id:any) => {
if(id){
const files = manifest[id]
if(files){
files.forEach((file:any)=>{
links += renderPreloadLink(file)
})
}
}
});
return links
}
//文件格式
function renderPreloadLink(file:any){
if(file.endsWith('.js')){
return ``
}else if(file.endsWith('.css')){
return ``
}else if(file.endsWith('.woff')){
return ``
}else if(file.endsWith('.woff2')){
return ``
}else if(file.endsWith('.gif')){
return ``
}else if(file.endsWith('.jpg')){
return ``
}else if(file.endsWith('.png')){
return ``
}else{
return ''
}
}