Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active April 26, 2020 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/8b5a59d655fa43933946517029ebbf3b to your computer and use it in GitHub Desktop.
Save mizchi/8b5a59d655fa43933946517029ebbf3b to your computer and use it in GitHub Desktop.
import Vue from "vue";
import { createRenderer } from "vue-server-renderer";
import * as vueCompiler from "vue-template-compiler";
const renderer = createRenderer();
const directives = {};
export async function compile(
template: string,
props: any
) {
const compiled = vueCompiler.compile(template, {
directives
});
const app = new Vue({
data: props,
directives,
// template,
render(h) {
const id = (i: any) => i;
const fn = new Function("_c", "_v", "_s", "_e", compiled.render).bind(
props
);
return fn(h, id, id, id);
}
});
const html = await renderer.renderToString(app);
return {
type: "vue",
html,
props,
code: "" // TODO
};
}
// ## How to use
//
// const template = `<div>
// <h1>Hello World - {{count}}</h1>
// <span v-if="count > 3">over 3</span>
// </div>`;
// compile(template, { count: 6 }).then(console.log);
//
// ## Out
//
// {
// type: 'vue',
// html: '<div data-server-rendered="true"><h1>Hello World - 6</h1> <span>over 3</span></div>',
// props: { count: 6 },
// code: ''
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment