feat(server-renderer): support on-the-fly template compilation (#707)

This commit is contained in:
Dmitry Sharshakov
2020-02-10 22:37:35 +03:00
committed by GitHub
parent cfadb98011
commit 6d10a6c772
3 changed files with 157 additions and 7 deletions

View File

@@ -11,7 +11,8 @@ import {
Portal,
ShapeFlags,
ssrUtils,
Slots
Slots,
warn
} from 'vue'
import {
isString,
@@ -19,10 +20,14 @@ import {
isArray,
isFunction,
isVoidTag,
escapeHtml
escapeHtml,
NO,
generateCodeFrame
} from '@vue/shared'
import { compile } from '@vue/compiler-ssr'
import { ssrRenderAttrs } from './helpers/ssrRenderAttrs'
import { SSRSlots } from './helpers/ssrRenderSlot'
import { CompilerError } from '@vue/compiler-dom'
const {
isVNode,
@@ -126,6 +131,44 @@ function renderComponentVNode(
}
}
type SSRRenderFunction = (
ctx: any,
push: (item: any) => void,
parentInstance: ComponentInternalInstance
) => void
const compileCache: Record<string, SSRRenderFunction> = Object.create(null)
function ssrCompile(
template: string,
instance: ComponentInternalInstance
): SSRRenderFunction {
const cached = compileCache[template]
if (cached) {
return cached
}
const { code } = compile(template, {
isCustomElement: instance.appContext.config.isCustomElement || NO,
isNativeTag: instance.appContext.config.isNativeTag || NO,
onError(err: CompilerError) {
if (__DEV__) {
const message = `Template compilation error: ${err.message}`
const codeFrame =
err.loc &&
generateCodeFrame(
template as string,
err.loc.start.offset,
err.loc.end.offset
)
warn(codeFrame ? `${message}\n${codeFrame}` : message)
} else {
throw err
}
}
})
return (compileCache[template] = Function(code)())
}
function renderComponentSubTree(
instance: ComponentInternalInstance
): ResolvedSSRBuffer | Promise<ResolvedSSRBuffer> {
@@ -134,6 +177,10 @@ function renderComponentSubTree(
if (isFunction(comp)) {
renderVNode(push, renderComponentRoot(instance), instance)
} else {
if (!comp.ssrRender && !comp.render && isString(comp.template)) {
comp.ssrRender = ssrCompile(comp.template, instance)
}
if (comp.ssrRender) {
// optimized
// set current rendering instance for asset resolution
@@ -143,11 +190,10 @@ function renderComponentSubTree(
} else if (comp.render) {
renderVNode(push, renderComponentRoot(instance), instance)
} else {
// TODO on the fly template compilation support
throw new Error(
`Component ${
comp.name ? `${comp.name} ` : ``
} is missing render function.`
} is missing template or render function.`
)
}
}