81 lines
1.9 KiB
JavaScript
81 lines
1.9 KiB
JavaScript
|
import { renderToString as renderToString_ } from '@vue/server-renderer';
|
||
|
import { escapeInject, dangerouslySkipEscape } from 'vite-plugin-ssr/server';
|
||
|
|
||
|
import { createApp } from './app';
|
||
|
import { useUser } from '../stores/user';
|
||
|
import logoUrl from './logo.svg';
|
||
|
|
||
|
async function renderToString(app) {
|
||
|
let err;
|
||
|
|
||
|
// Workaround: renderToString_() swallows errors in production, see https://github.com/vuejs/core/issues/7876
|
||
|
app.config.errorHandler = (err_) => { // eslint-disable-line no-param-reassign
|
||
|
err = err_;
|
||
|
};
|
||
|
|
||
|
const appHtml = await renderToString_(app);
|
||
|
|
||
|
if (err) {
|
||
|
throw err;
|
||
|
}
|
||
|
|
||
|
return appHtml;
|
||
|
}
|
||
|
|
||
|
async function render(pageContext) {
|
||
|
const appHtml = await renderToString(pageContext.app);
|
||
|
|
||
|
// See https://vite-plugin-ssr.com/head
|
||
|
const { documentProps } = pageContext.exports;
|
||
|
const title = (documentProps && documentProps.title) || 'shack';
|
||
|
const desc = (documentProps && documentProps.description) || 'Shack';
|
||
|
|
||
|
const documentHtml = escapeInject`
|
||
|
<!DOCTYPE html>
|
||
|
<html lang="en">
|
||
|
<head>
|
||
|
<meta charset="UTF-8" />
|
||
|
<link rel="icon" href="${logoUrl}" />
|
||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||
|
<meta name="description" content="${desc}" />
|
||
|
<title>${title}</title>
|
||
|
</head>
|
||
|
<body>
|
||
|
<div id="app">${dangerouslySkipEscape(appHtml)}</div>
|
||
|
</body>
|
||
|
</html>
|
||
|
`;
|
||
|
|
||
|
return {
|
||
|
documentHtml,
|
||
|
};
|
||
|
}
|
||
|
|
||
|
async function onBeforeRender(pageContext) {
|
||
|
if (!pageContext.Page) {
|
||
|
throw new Error('My render() hook expects pageContext.Page to be defined');
|
||
|
}
|
||
|
|
||
|
const { app, store } = createApp(pageContext);
|
||
|
const userStore = useUser();
|
||
|
|
||
|
userStore.user = pageContext.session.user;
|
||
|
|
||
|
return {
|
||
|
pageContext: {
|
||
|
app,
|
||
|
initialState: store.state.value,
|
||
|
pageData: {
|
||
|
user: pageContext.session.user,
|
||
|
},
|
||
|
},
|
||
|
};
|
||
|
}
|
||
|
|
||
|
export {
|
||
|
render,
|
||
|
onBeforeRender,
|
||
|
};
|
||
|
|
||
|
export const passToClient = ['urlPathname', 'initialState', 'pageData'];
|