聊聊Vue.js的template编译的问题

2020-06-16 05:53:19易采站长站整理

}
}
}
/*Github:https://github.com/answershuto*/
// check cache
/*有缓存的时候直接取出缓存中的结果即可*/
const key = options.delimiters
? String(options.delimiters) + template
: template
if (functionCompileCache[key]) {
return functionCompileCache[key] }

// compile
/*编译*/
const compiled = compile(template, options)

// check compilation errors/tips
if (process.env.NODE_ENV !== 'production') {
if (compiled.errors && compiled.errors.length) {
warn(
`Error compiling template:nn${template}nn` +
compiled.errors.map(e => `- ${e}`).join('n') + 'n',
vm
)
}
if (compiled.tips && compiled.tips.length) {
compiled.tips.forEach(msg => tip(msg, vm))
}
}

// turn code into functions
const res = {}
const fnGenErrors = [] /*将render转换成Funtion对象*/
res.render = makeFunction(compiled.render, fnGenErrors)
/*将staticRenderFns全部转化成Funtion对象 */
const l = compiled.staticRenderFns.length
res.staticRenderFns = new Array(l)
for (let i = 0; i < l; i++) {
res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i], fnGenErrors)
}

// check function generation errors.
// this should only happen if there is a bug in the compiler itself.
// mostly for codegen development use
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
warn(
`Failed to generate render function:nn` +
fnGenErrors.map(({ err, code }) => `${err.toString()} innn$[code]n`).join('n'),
vm
)
}
}

/*存放在缓存中,以免每次都重新编译*/
return (functionCompileCache[key] = res)
}

我们可以发现,在闭包中,会有一个functionCompileCache对象作为缓存器。


/*作为缓存,防止每次都重新编译*/
const functionCompileCache: {
[key: string]: CompiledFunctionResult;
} = Object.create(null)

在进入compileToFunctions以后,会先检查缓存中是否有已经编译好的结果,如果有结果则直接从缓存中读取。这样做防止每次同样的模板都要进行重复的编译工作。


// check cache
/*有缓存的时候直接取出缓存中的结果即可*/
const key = options.delimiters
? String(options.delimiters) + template
: template
if (functionCompileCache[key]) {
return functionCompileCache[key] }

在compileToFunctions的末尾会将编译结果进行缓存


/*存放在缓存中,以免每次都重新编译*/