vue3编译器

285 阅读5分钟

我正在参加「掘金·启航计划」

编译器其实就是一段JavaScript代码程序,它将一种语言A编译成另一种语言B,其中前者A通常被叫做源代码,后者B通常被叫做目标代码。例如我们vue的前端项目.vue文件夹一般为源代码,而编译后dist文件里的.js文件即为目标代码,这个过程就被称为编译。

Vue的编译器

vue.js的源代码就是组件的模板代码,目标代码就会能够在浏览器上运行的JavaScript代码,目标代码其实就是渲染函数(render函数)。

一个简单的vue.js模板编译器的工作流程如下:

模板代码

<div>
<span>vue</span>
</div>

AST

const ast = {
    type: 'Root',
    children: [
        {
            type: 'Element',
            tag: 'div',
            children: [
                {
                    type:'Element',
                    tag: 'span',              
                    children: [
                        {
                            type: 'Text',
                            content: 'vue'
                        }
                    ]
                }
            ]
        }
    ]
}

渲染函数

    function render(_ctx, _cache, $props, $setup, $data, $options) {
  return (_openBlock(), _createElementBlock("div", null, [
    _createElementVNode("span", null, "vue ")
  ]))
}

Vue 3 Template Explorer

parse函数

vue.js 通过封装parse函数,将模板解析为AST,此时的AST只是被简单的翻译,并没有实际的可用性。

transform函数

transform 函数将原始AST转换为可用于渲染的目标AST,同时为各节点小创建代码生成器,同时对其进行优化。

genderate函数

通过genderate函数生成最终可运行代码片段。

部分源码功能

$mount

编译器的入口,只做了一件事情,得到组件的渲染函数,将其设置到this.$options上.

原创作者李永宁
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
// 挂载点
  el = el && query(el)
  // 挂载点不能是 body 或者 html
 if (el === document.body || el === document.documentElement) {
 process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
    }
// 配置项
const options = this.$options
//如果用户提供了 render 配置项,则直接跳过编译阶段,否则进入编译阶段。
//解析 template 和 el,并转换为 render 函数。
//优先级:render > template > el
if (!options.render) {
let template = options.template
if (template) {
// 处理 template 选项
      if (typeof template === 'string') {
 if (template.charAt(0) === '#') {
 // { template: '#app' },template 是一个 id 选择器,则获取该元素的 innerHtml 作为模版。
 template = idToTemplate(template)
 if (process.env.NODE_ENV !== 'production' && !template) {
 warn(
              `Template element not found or is empty: ${options.template}`,
              this
     )
    }
    }
  } else if (template.nodeType) {
 // template 是一个正常的元素,获取其 innerHtml 作为模版
 template = template.innerHTMLelse {
 if (process.env.NODE_ENV !== 'production') {
 warn('invalid template option:' + template, this)
 }
 return this
 }
 }else if(el){
 // 设置了 el 选项,获取 el 选择器的 outerHtml 作为模版
 template = getOuterHTML(el)
 }
 if (template) {
 // 模版就绪,进入编译阶段
 if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
 mark('compile')
 }
 // 编译模版,得到 动态渲染函数和静态渲染函数
 const { render, staticRenderFns } = compileToFunctions(template, {
 // 在非生产环境下,编译时记录标签属性在模版字符串中开始和结束的位置索引
 outputSourceRange: process.env.NODE_ENV !== 'production',
 shouldDecodeNewlines,
 shouldDecodeNewlinesForHref,
 // 界定符,默认 {{}}
 delimiters: options.delimiters, 
 // 是否保留注释
 comments: options.comments
 }, this)
 // 将两个渲染函数放到 this.$options 上
 options.render = render
 options.staticRenderFns = staticRenderFns
 if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
 mark('compile end')
 measure(`vue ${this._name} compile`'compile''compile end')
 }
 }
 }
 // 执行挂载
 return mount.call(this, el, hydrating)
 }

compileToFunctions

执行编译函数,得到编译结果compiled,处理编译期间产生的error和tip,分别输出到控制台。 将编译得到的字符串代码通过new Function(codeStr) 转换成可执行的函数。 缓存编译结果。

return function compileToFunctions(
  template: string,
  options?: CompilerOptions,
  vm?: Component
): CompiledFunctionResult {
  // 传递进来的编译选项
  options = extend({}, options)
  // 日志
  const warn = options.warn || baseWarn
  delete options.warn

  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production') {
    // 检测可能的 CSP 限制
    try {
      new Function('return 1')
    } catch (e) {
      if (e.toString().match(/unsafe-eval|CSP/)) {
        // 看起来你在一个 CSP 不安全的环境中使用完整版的 Vue.js,模版编译器不能工作在这样的环境中。
        // 考虑放宽策略限制或者预编译你的 template 为 render 函数
        warn(
          'It seems you are using the standalone build of Vue.js in an ' +
          'environment with Content Security Policy that prohibits unsafe-eval. ' +
          'The template compiler cannot work in this environment. Consider ' +
          'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
          'templates into render functions.'
        )
      }
    }
  }

  // 如果有缓存,则跳过编译,直接从缓存中获取上次编译的结果
  const key = options.delimiters
    ? String(options.delimiters) + template
    : template
  if (cache[key]) {
    return cache[key]
  }

  // 执行编译函数,得到编译结果
  const compiled = compile(template, options)

  // 检查编译期间产生的 error 和 tip,分别输出到控制台
  if (process.env.NODE_ENV !== 'production') {
    if (compiled.errors && compiled.errors.length) {
      if (options.outputSourceRange) {
        compiled.errors.forEach(e => {
          warn(
            `Error compiling template:\n\n${e.msg}\n\n` +
            generateCodeFrame(template, e.start, e.end),
            vm
          )
        })
      } else {
        warn(
          `Error compiling template:\n\n${template}\n\n` +
          compiled.errors.map(e => `- ${e}`).join('\n') + '\n',
          vm
        )
      }
    }
    if (compiled.tips && compiled.tips.length) {
      if (options.outputSourceRange) {
        compiled.tips.forEach(e => tip(e.msg, vm))
      } else {
        compiled.tips.forEach(msg => tip(msg, vm))
      }
    }
  }

  // 转换编译得到的字符串代码为函数,通过 new Function(code) 实现
  // turn code into functions
  const res = {}
  const fnGenErrors = []
  res.render = createFunction(compiled.render, fnGenErrors)
  res.staticRenderFns = compiled.staticRenderFns.map(code => {
    return createFunction(code, fnGenErrors)
  })

  // 处理上面代码转换过程中出现的错误,这一步一般不会报错,除非编译器本身出错了
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production') {
    if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
      warn(
        `Failed to generate render function:\n\n` +
        fnGenErrors.map(({ err, code }) => `${err.toString()} in\n\n${code}\n`).join('\n'),
        vm
      )
    }
  }

  // 缓存编译结果
  return (cache[key] = res)
}

compile

选项合并,将 options 配置项 合并到 finalOptions(baseOptions) 中,得到最终的编译配置对象。 调用核心编译器 baseCompile 得到编译结果。 将编译期间产生的 error 和 tip 挂载到编译结果上,返回编译结果。

function compile(
  template: string,
  options?: CompilerOptions
): CompiledResult {
  // 以平台特有的编译配置为原型创建编译选项对象
  const finalOptions = Object.create(baseOptions)
  const errors = []
  const tips = []

  // 日志,负责记录将 error 和 tip
  let warn = (msg, range, tip) => {
    (tip ? tips : errors).push(msg)
  }

  // 如果存在编译选项,合并 options 和 baseOptions
  if (options) {
    // 开发环境走
    if (process.env.NODE_ENV !== 'production' && options.outputSourceRange) {
      // $flow-disable-line
      const leadingSpaceLength = template.match(/^\s*/)[0].length

      // 增强 日志 方法
      warn = (msg, range, tip) => {
        const data: WarningMessage = { msg }
        if (range) {
          if (range.start != null) {
            data.start = range.start + leadingSpaceLength
          }
          if (range.end != null) {
            data.end = range.end + leadingSpaceLength
          }
        }
        (tip ? tips : errors).push(data)
      }
    }

    /**
     * 将 options 中的配置项合并到 finalOptions
     */

    // 合并自定义 module
    if (options.modules) {
      finalOptions.modules =
        (baseOptions.modules || []).concat(options.modules)
    }
    // 合并自定义指令
    if (options.directives) {
      finalOptions.directives = extend(
        Object.create(baseOptions.directives || null),
        options.directives
      )
    }
    // 拷贝其它配置项
    for (const key in options) {
      if (key !== 'modules' && key !== 'directives') {
        finalOptions[key] = options[key]
      }
    }
  }

  // 日志
  finalOptions.warn = warn

  // 到这里为止终于到重点了,调用核心编译函数,传递模版字符串和最终的编译选项,得到编译结果
  // 前面做的所有事情都是为了构建平台最终的编译选项
  const compiled = baseCompile(template.trim(), finalOptions)
  if (process.env.NODE_ENV !== 'production') {
    detectErrors(compiled.ast, warn)
  }
  // 将编译期间产生的错误和提示挂载到编译结果上
  compiled.errors = errors
  compiled.tips = tips
  return compiled
}

baseOptions

export const baseOptions: CompilerOptions = {
  expectHTML: true,
  // 处理 class、style、v-model
  modules,
  // 处理指令
  // 是否是 pre 标签
  isPreTag,
  // 是否是自闭合标签
  isUnaryTag,
  // 规定了一些应该使用 props 进行绑定的属性
  mustUseProp,
  // 可以只写开始标签的标签,结束标签浏览器会自动补全
  canBeLeftOpenTag,
  // 是否是保留标签(html + svg)
  isReservedTag,
  // 获取标签的命名空间
  getTagNamespace,
  staticKeys: genStaticKeys(modules)
}

baseCompile

将 html 模版解析成 ast 对 ast 树进行静态标记 将 ast 生成渲染函数 静态渲染函数放到 code.staticRenderFns 数组中 code.render 为动态渲染函数 在将来渲染时执行渲染函数得到 vnode

function baseCompile (
  template: string,
  options: CompilerOptions
): CompiledResult {
  // 将模版解析为 AST,每个节点的 ast 对象上都设置了元素的所有信息,比如,标签信息、属性信息、插槽信息、父节点、子节点等。
  // 具体有那些属性,查看 start 和 end 这两个处理开始和结束标签的方法
  const ast = parse(template.trim(), options)
  // 优化,遍历 AST,为每个节点做静态标记
  // 标记每个节点是否为静态节点,然后进一步标记出静态根节点
  // 这样在后续更新中就可以跳过这些静态节点了
  // 标记静态根,用于生成渲染函数阶段,生成静态根节点的渲染函数
  if (options.optimize !== false) {
    optimize(ast, options)
  }
  // 从 AST 生成渲染函数,生成像这样的代码,比如:code.render = "_c('div',{attrs:{"id":"app"}},_l((arr),function(item){return _c('div',{key:item},[_v(_s(item))])}),0)"
  const code = generate(ast, options)
  return {
    ast,
    render: code.render,
    staticRenderFns: code.staticRenderFns
  }
}