前言
Vue 源码解读(4)—— 异步更新 最后说到刷新 watcher 队列,执行每个 watcher.run
方法,由 watcher.run
调用 watcher.get
,从而执行 watcher.getter
方法,进入实际的更新阶段。这个流程如果不熟悉,建议大家再去读一下这篇文章。
当更新一个渲染 watcher 时,执行的是 updateComponent
方法:
// /src/core/instance/lifecycle.js
const updateComponent = () => {
// 执行 vm._render() 函数,得到 虚拟 DOM,并将 vnode 传递给 _update 方法,接下来就该到 patch 阶段了
vm._update(vm._render(), hydrating)
}
可以看到每次更新前都需要先执行一下 vm._render()
方法,vm._render 就是大家经常听到的 render 函数,由两种方式得到:
-
用户自己提供,在编写组件时,用 render 选项代替模版
-
由编译器编译组件模版生成 render 选项
今天我们就来深入研究编译器,看看它是怎么将我们平时编写的类 html 模版编译成 render 函数的。
编译器的核心由三部分组成:
-
解析,将类 html 模版转换为 AST 对象
-
优化,也叫静态标记,遍历 AST 对象,标记每个节点是否为静态节点,以及标记出静态根节点
-
生成渲染函数,将 AST 对象生成渲染函数
由于编译器这块儿的代码量太大,所以,将这部分知识拆成三部分来讲,第一部分就是:解析。
目标
深入理解 Vue 编译器的解析过程,理解如何将类 html 模版字符串转换成 AST 对象。
源码解读
接下来我们去源码中找答案。
阅读建议
由于解析过程代码量巨大,所以建议大家抓住主线:“解析类 HTML 字符串模版,生成 AST 对象”,而这个 AST 对象就是我们最终要得到的结果,所以大家在阅读的过程中,要动手记录这个 AST 对象,这样有助于理解,也让你不那么容易迷失。
入口 - $mount
编译器的入口位置在 /src/platforms/web/entry-runtime-with-compiler.js
,有两种方式找到这个入口
-
断点调试,Vue 源码解读(2)—— Vue 初始化过程 中讲到,初始化的最后一步是执行
$mount
进行挂载,在全量的 Vue 包中这一步就会进入编译阶段。 -
通过 rollup 的配置文件一步步的去找
/src/platforms/web/entry-runtime-with-compiler.js
/**
* 编译器的入口
* 运行时的 Vue.js 包就没有这部分的代码,通过 打包器 结合 vue-loader + vue-compiler-utils 进行预编译,将模版编译成 render 函数
*
* 就做了一件事情,得到组件的渲染函数,将其设置到 this.$options 上
*/
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
// 挂载点
el = el && query(el)
// 挂载点不能是 body 或者 html
/* istanbul ignore if */
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
// resolve template/el and convert to render function
/**
* 如果用户提供了 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)
/* istanbul ignore if */
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.innerHTML
} else {
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) {
// 模版就绪,进入编译阶段
/* istanbul ignore if */
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
/* istanbul ignore if */
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
/src/compiler/to-function.js
/**
* 1、执行编译函数,得到编译结果 -> compiled
* 2、处理编译期间产生的 error 和 tip,分别输出到控制台
* 3、将编译得到的字符串代码通过 new Function(codeStr) 转换成可执行的函数
* 4、缓存编译结果
* @param { string } template 字符串模版
* @param { CompilerOptions } options 编译选项
* @param { Component } vm 组件实例
* @return { render, staticRenderFns }
*/
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
/src/compiler/create-compiler.js
/**
* 编译函数,做了两件事:
* 1、选项合并,将 options 配置项 合并到 finalOptions(baseOptions) 中,得到最终的编译配置对象
* 2、调用核心编译器 baseCompile 得到编译结果
* 3、将编译期间产生的 error 和 tip 挂载到编译结果上,返回编译结果
* @param {*} template 模版
* @param {*} options 配置项
* @returns
*/
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
/src/platforms/web/compiler/options.js
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
/src/compiler/index.js
/**
* 在这之前做的所有的事情,只有一个目的,就是为了构建平台特有的编译选项(options),比如 web 平台
*
* 1、将 html 模版解析成 ast
* 2、对 ast 树进行静态标记
* 3、将 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) {