在最开始的章节提到过,我们在使用 vue-cli
创建项目的时候,提供了两个版本供我们使用, Runtime Only
版本和 Runtime + Compiler
版本。Runtime Only
版本是不包含编译器的,在项目打包的时候会把模板编译成 render
函数,也叫预编译。Runtime + Compiler
版本包含编译器,可以把编译过程放在运行时做。
入口
这一块代码量比较多,主要是对各种情况做了一些边界处理。这里只关注主流程。对细节感兴趣的伙伴们可以自行去研究。一般我们使用 Runtime + Compiler
版本可能比较多一些,先来找到入口:
// src/platforms/web/entry-runtime-with-compiler.js
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
// ...
if (!options.render) {
// 模版就绪,进入编译阶段
if (template) {
// 编译模版,得到 动态渲染函数和静态渲染函数
const {
render, staticRenderFns } = compileToFunctions(template, {
// 在非生产环境下,编译时记录标签属性在模版字符串中开始和结束的位置索引
outputSourceRange: process.env.NODE_ENV !== 'production',
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
// 界定符,默认 {
{}}
delimiters: options.delimiters,
// 是否保留注释
comments: options.comments
}, this)
}
}
}
compileToFunctions
方法就是把 template
编译而得到 render
以及 staticRenderFns
。
compileToFunctions
// src/platforms/web/compiler/index.js
import {
baseOptions } from './options'
import {
createCompiler } from 'compiler/index'
const {
compile, compileToFunctions } = createCompiler(baseOptions)
export {
compile, compileToFunctions }
createCompiler
// src/compiler/index.js
export const createCompiler = createCompilerCreator(function baseCompile (
template: string,
options: CompilerOptions
): CompiledResult {
// 将模版解析为 AST
const ast = parse(template.trim(), options)
// 优化 AST,静态标记
if (options.optimize !== false) {
optimize(ast, options)
}
// 生成渲染函数,,将 ast 转换成可执行的 render 函数的字符串形式
// code = {
// render: `with(this){return ${_c(tag, data, children, normalizationType)}}`,
// staticRenderFns: [_c(tag, data, children, normalizationType), ...]
// }
const code = generate(ast, options)
return {
ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
})
createCompiler
是通过调用 createCompilerCreator
返回的,这里传入了一个 baseCompile
函数作为参数,这个函数是重点,编译的核心过程就是在这个函数中执行的。
createCompilerCreator
// src/compiler/create-compiler.js
export function createCompilerCreator (baseCompile: Function): Function {
return function createCompiler (baseOptions: CompilerOptions) {
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)
}
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
// merge custom modules
if (options.modules) {
finalOptions.modules =
(baseOptions.modules || []).concat(options.modules)
}
// merge custom directives
if (options.directives) {
finalOptions.directives = extend(
Object.create(baseOptions.directives || null),
options.directives
)
}
// copy other options
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
}
return {
compile,
compileToFunctions: createCompileToFunctionFn(compile)
}
}
}
createCompilerCreator
返回了一个 createCompiler
函数,createCompiler
返回了一个对象,包括了 compile
和 compileToFunctions
,这个 compileToFunctions
对应的就是 $mount
中调用的 compileToFunctions
方法。在 createCompiler
函数内定义了 compile
方法,并把它传递给 createCompileToFunctionFn
,compile
主要目的就是对特有平台的配置项做一些合并,如 web 平台和处理一些在编译期间产生的错误。
createCompileToFunctionFn
// src/compiler/to-function.js
export function createCompileToFunctionFn (compile: Function): Function {
const cache = Object.create(null)
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') {
// detect possible CSP restriction
// 检测可能的 CSP 限制
try {
new Function('return 1')
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
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.'
)
}
}
}
// check cache
// 如果有缓存,则跳过编译,直接从缓存中获取上次编译的结果
const key = options.delimiters
? String(options.delimiters) + template
: template
if (cache[key]) {
return cache[key]
}
// compile
// 执行编译函数,得到编译结果
const compiled = compile(template, options)
// check compilation errors/tips
// 检查编译期间产生的 errors/tips,分别输出到控制台
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))
}
}
}
// turn code into functions
// 转换编译得到的字符串代码为函数,通过 new Function(code) 实现
const res = {
}
const fnGenErrors = []
res.render = createFunction(compiled.render, fnGenErrors)
res.staticRenderFns = compiled.staticRenderFns.map(code => {
return createFunction(code, 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:\n\n` +
fnGenErrors.map(({
err, code }) => `${
err.toString()} in\n\n${
code}\n`).join('\n'),
vm
)
}
}
// 缓存编译结果
return (cache[key] = res)
}
}
createCompileToFunctionFn
返回了 compileToFunctions
这个就是我们要找的最终定义所在了,它主要做了这么几件事:
- 执行编译函数得到编译结果。
- 将编译得到的字符串代码转换成可执行的函数。
- 处理异常
- 缓存
小结
通过以上的代码可以看出真正编译个过程就在 createCompilerCreator
函数传递的 baseCompile
中,主要分为这么几个部分:
- 将模板解析成 AST
const ast = parse(template.trim(), options)
- 优化 AST (静态标记)
optimize(ast, options)
- 生成代码字符串
const code = generate(ast, options)
之所以在真正编译之前做了这么多前戏,目的就是为了对不同平台做一些处理。下面主要针对这三个部分看看做了一些什么事情。
parse
parse
主要作用就是将模板解析成 AST,它是一种抽象语法树。这个过程比较复杂,它会在每个节点的 AST 对象上设置元素的所有信息,比如:父节点、子节点、标签信息、属性信息、插槽信息等等。在期间会用到许多正则表达式对模板进行匹配。
parse
// src/compiler/parser/index.js
export function parse (
template: string,
options: CompilerOptions
): ASTElement | void {
warn = options.warn || baseWarn
// 是否为 pre 标签
platformIsPreTag = options.isPreTag || no
// 必须使用 props 进行绑定的属性
platformMustUseProp = options.mustUseProp || no
// 获取标签的命名空间
platformGetTagNamespace = options.getTagNamespace || no
// 是否是保留标签(html + svg)
const isReservedTag = options.isReservedTag || no
// 是否为一个组件
maybeComponent = (el: ASTElement) => !!(
el.component ||
el.attrsMap[':is'] ||
el.attrsMap['v-bind:is'] ||
!(el.attrsMap.is ? isReservedTag(el.attrsMap.is) : isReservedTag(el.tag))
)
// 分别获取 options.modules 下的 class、model、style 三个模块中的 transformNode、preTransformNode、postTransformNode 方法
// 负责处理元素节点上的 class、style、v-model
transforms = pluckModuleFunction(options.modules, 'transformNode')
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode')
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode')
// 界定符,比如: {
{}}
delimiters = options.delimiters
const stack = []
// 空格选项
const preserveWhitespace = options.preserveWhitespace !== false
const whitespaceOption = options.whitespace
// 根节点,以 root 为根,处理后的节点都会按照层级挂载到 root 下,最后 return 的就是 root,一个 ast 语法树
let root
// 当前元素的父元素
let currentParent
let inVPre = false
let inPre = false
let warned = false
function warnOnce (msg, range) {
if (!warned) {
warned = true
warn(msg, range)
}
}
// 由于代码比较长,后面几个方法单独拿出来。
function closeElement (element) {
/*...*/ }
function trimEndingWhitespace (el) {
/*...*/ }
function checkRootConstraints (el) {
/*...*/ }
parseHTML(template, {
/*...*/
})
return root
}
parse
接收两个参数 template
和 options
,也就是模板字符串和配置选项,options
定义在 /src/platforms/web/compiler/options
中,这里主要是不同的平台(web 和 weex)的配置选项不同。
closeElement
// src/compiler/parser/index.js
function closeElement (element) {
// 移除节点末尾的空格
trimEndingWhitespace(element)
// 当前元素不再 pre 节点内,并且也没有被处理过
if (!inVPre && !element.processed) {
// 分别处理元素节点的 key、ref、插槽、自闭合的 slot 标签、动态组件、class、style、v-bind、v-on、其它指令和一些原生属性
element = processElement(element, options)
}
// 处理根节点上存在 v-if、v-else-if、v-else 指令的情况
// 如果根节点存在 v-if 指令,则必须还提供一个具有 v-else-if 或者 v-else 的同级别节点,防止根元素不存在
// tree management
if (!stack.length && element !== root) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
if (process.env.NODE_ENV !== 'production') {
checkRootConstraints(element)
}
addIfCondition(root, {
exp: element.elseif,
block: element
})
} else if (process.env.NODE_ENV !== 'production') {
warnOnce(
`Component template should contain exactly one root element. ` +
`If you are using v-if on multiple elements, ` +
`use v-else-if to chain them instead.`,
{
start: element.start }
)
}
}
// 建立父子关系,将自己放到父元素的 children 数组中,然后设置自己的 parent 属性为 currentParent
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent)
} else {
if (element.slotScope) {
// scoped slot
// keep it in the children list so that v-else(-if) conditions can
// find it as the prev node.
const name = element.slotTarget || '"default"'
; (currentParent.scopedSlots || (currentParent.scopedSlots = {
}))[name] = element
}
currentParent.children.push(element)
element.parent = currentParent
}
}
// 设置子元素,将自己的所有非插槽的子元素设置到 element.children 数组中
// final children cleanup
// filter out scoped slots
element.children = element.children.filter(c => !(c: any).slotScope)
// remove trailing whitespace node again
trimEndingWhitespace(element)
// check pre state
if (element.pre) {
inVPre = false
}
if (platformIsPreTag(element