-
Notifications
You must be signed in to change notification settings - Fork 9
/
templateCompiler.js
62 lines (53 loc) · 1.95 KB
/
templateCompiler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import {renderCompiler} from "./renderCompiler"
const templateCompiler = require('vue-template-compiler')
function toFunction(code, isFunctional) {
return `function (${isFunctional ? `_h,_vm` : ``}) {${code}}`
}
function getMarkRange(code, startMark, endMark) {
if (!code || !code.indexOf) {
// TODO handle edge error
return false
}
return {
start: code.indexOf(startMark) + 1,
end: code.lastIndexOf(endMark)
}
}
function getFunctionBody(code) {
const range = getMarkRange(code, '{', '}')
return code.substring(range.start, range.end)
}
function getArrayItems(code) {
const range = getMarkRange(code, '[', ']')
return code.substring(range.start, range.end)
.split('function')
.filter((functionBodyStr) => Boolean(functionBodyStr))
.map(getFunctionBody)
}
const renderSeparator = '/* renderSeparator */'
export function compileTemplate(source, options) {
const isFunctional = options?.filename
?.includes(options?.functionalComponentFileIdentifier || '.functional')
const {ast, render, staticRenderFns, tips, errors} = templateCompiler.compile(source, options)
// TODO rm semicolon && \n : https://babeljs.io/docs/en/options#minified
let code = `var render = ${toFunction(render, isFunctional)}` + ';'+ renderSeparator
const hasStaticRenders = staticRenderFns.length
if (hasStaticRenders) {
code += `var staticRenderFns = [${staticRenderFns.map((render) => toFunction(render, isFunctional))}]`
}
const [compiledRender, compiledStaticRenders] = renderCompiler(code, {transforms: {stripWithFunctional: isFunctional}}).split(renderSeparator)
return {
ast,
render: getFunctionBody(compiledRender),
staticRenderFns: hasStaticRenders ? getArrayItems(compiledStaticRenders) : staticRenderFns,
tips,
errors
}
}
export function extendTemplateCompiler(obj) {
for (const key in templateCompiler) {
obj[key] = templateCompiler[key]
}
obj.ssrCompile = compileTemplate
obj.compile = compileTemplate
}