vite-ssr-vue
Version:
Vite utility for vue3 server side rendering
75 lines (70 loc) • 1.66 kB
JavaScript
import { ref, onMounted, createSSRApp } from 'vue';
const unserialize = (state) => {
try {
return JSON.parse(state || "{}");
} catch (e) {
throw new Error(`[SSR] On state unserialization - ${e.message}`);
}
};
const ClientOnly = {
name: "ClientOnly",
setup(props, { slots }) {
const show = ref(false);
onMounted(() => {
show.value = true;
});
return () => show.value && slots.default ? slots.default() : null;
}
};
const createViteSsrVue = async (App, options = {}) => {
const app = createSSRApp(App, options.rootProps);
const serializer = options.serializer || unserialize;
const initialState = await serializer(window.__INITIAL_STATE__);
const url = window.location;
let store, router, pinia;
if (options.created) {
({ store, router, pinia } = await options.created({
url,
app,
isClient: true,
initialState
}) || {});
}
if (store && initialState.state) {
store.replaceState(initialState.state);
}
if (pinia && initialState.pinia) {
pinia.state.value = initialState.pinia;
}
if (router) {
await router.isReady();
}
if (options.mounted) {
await options.mounted({
url,
app,
isClient: true,
initialState,
store,
pinia,
router
});
}
if (options.rendered) {
await options.rendered({
url,
app,
isClient: true,
initialState,
store,
pinia,
router
});
}
app.mount(
options?.mount?.rootContainer || "#app",
options?.mount?.isHydrate || true,
options?.mount?.isSVG || true
);
};
export { ClientOnly, createViteSsrVue as default };