Vue 模版编译原理

99 阅读1分钟

template

  • vue 中的模板template无法被浏览器解析渲染,因为这不属于浏览器的标准,不是正确的HTML语法

模板编译

  • 将template转化成一个JavaScript 函数,这样浏览器就可以执行这一个函数并渲染出对应的HTML元素,就可以让视图跑起来了,这一个转化的过程,就成为模板编译
  • 模板编译又分三个阶段,解析parse,优化optimize,生成generate,最终生成可执行函数render
  • 模板编译是在构建时完成的,而不是在运行时。这样可以避免运行时解析和编译模板的性能损耗,提升应用的性能

模板编译三个阶段

  • 解析parse
    • 使用大量的正则表达式对template字符串进行解析,将标签、指令、属性等转化为抽象语法树AST
  • 优化optimize
    • 遍历AST,找到其中的一些静态节点并进行标记,方便在页面重渲染的时候进行diff比较时,直接跳过这一些静态节点,优化runtime 的性能
  • 生成generate
    • 将最终的AST转化为render函数字符串
  • 模板编译简易实现
// 解析器类
class Parser {
  constructor(template) {
    this.template = template
  }
 
  parse() {
    // 解析模板,生成AST
    // ...
  }
}
 
// AST 节点类
class ASTNode {
  constructor(type, tag, attrs, children) {
    this.type = type
    this.tag = tag
    this.attrs = attrs
    this.children = children
  }
}
 
// 代码生成器类
class CodeGenerator {
  constructor(ast) {
    this.ast = ast
  }
 
  generate() {
    // 生成渲染函数代码字符串
    // ...
  }
}
 
// 编译器类
class Compiler {
  constructor(template) {
    this.template = template
  }
 
  compile() {
    // 解析模板生成AST
    const parser = new Parser(this.template)
    const ast = parser.parse()
 
    // 生成渲染函数代码
    const generator = new CodeGenerator(ast)
    const code = generator.generate()
 
    return code
  }
}
 
// 使用示例
const template = `<div id="app">{{ message }}</div>`
 
const compiler = new Compiler(template)
const code = compiler.compile()
 
console.log(code)

------------------------------------------------------------------------------2024.6.2每日一题