vite-ssr-vue2
Version:
Vite utility for vue2 server side rendering
60 lines (56 loc) • 1.48 kB
JavaScript
import Vue from 'vue';
const unserialize = (state) => {
try {
return JSON.parse(state || "{}");
} catch (e) {
throw new Error(`[SSR] On state unserialization - ${e.message}`);
}
};
const createViteSsrVue = async (App, options = {}) => {
const serializer = options.serializer || unserialize;
const initialState = await serializer(window.__INITIAL_STATE__);
const url = window.location;
let store, router, app;
if (options.created) {
({ store, router, app } = await options.created({
url,
isClient: true,
initialState
}) || {});
}
const vueIns = app || new Vue({
...options.rootProps ? { propsData: options.rootProps } : {},
...router ? { router } : {},
...store ? { store } : {},
render: (h) => h(App)
});
if (options.mounted) {
await options.mounted({
url,
app: vueIns,
isClient: true,
initialState,
store,
router
});
}
if (store && initialState.state) {
store.replaceState(initialState.state);
}
if (options.rendered) {
await options.rendered({
url,
app: vueIns,
isClient: true,
initialState,
store,
router
});
}
if (router) {
router.onReady(() => vueIns.$mount(options?.mount?.rootContainer || "#app", options?.mount?.hydrating ?? true));
} else {
vueIns.$mount(options?.mount?.rootContainer || "#app", options?.mount?.hydrating ?? true);
}
};
export { createViteSsrVue as default };