7天深入Vue-模板编译(六)

模板编译

  • 模板编译得主要目标是将temolate 转换为渲染函数render

1.src\platforms\web\entry-runtime-with-compiler.js

const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
      const { render, staticRenderFns } = compileToFunctions(template, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns
}
  • compileToFunctions 将template转换为render函数

2.src\platforms\web\compiler\index.js

import { baseOptions } from './options'
import { createCompiler } from 'compiler/index'

const { compile, compileToFunctions } = createCompiler(baseOptions)

export { compile, compileToFunctions }

3.src\compiler\index.js

export const createCompiler = createCompilerCreator(function baseCompile (
  template: string,
  options: CompilerOptions
): CompiledResult {
  const ast = parse(template.trim(), options)
  if (options.optimize !== false) {
    optimize(ast, options)
  }
  const code = generate(ast, options)
  return {
    ast,
    render: code.render,
    staticRenderFns: code.staticRenderFns
  }
})

  • const ast = parse(template.trim(), options) 将模板解析成ast
  • 优化-optimize 优化器得作用是在AST中找出静态子树并打上标记。静态子树是在AST中永远不变得节点,如纯文本节点

4.src\compiler\parser\index.js

parseHTML(template, {})

5.src\compiler\codegen\index.js

export function generate (
  ast: ASTElement | void,
  options: CompilerOptions
): CodegenResult {
  const state = new CodegenState(options)
  const code = ast ? genElement(ast, state) : '_c("div")'
  return {
    render: `with(this){return ${code}}`,
    staticRenderFns: state.staticRenderFns
  }
}
  • 生成 render 函数,和静态render函数

你可能感兴趣的:(7天深入Vue-模板编译(六))