前言#
part2我们来分析插件和gencode的部分
另外如果没看过parse以及part1部分的可以去看下
坏蛋Dan:vue/compiler-core源码分析学习--day2: parse部分
坏蛋Dan:vue/compiler-core源码分析学习--day3: compile部分part1
nodeTransforms#
有些东西指令的加工或者二次加工我们在compiler-dom/compiler-sfc上面说过了,所以这里就不说跟着options传进来的了。
接下来的分析是跟着执行顺序以及getBaseTransformPreset这个方法来的。
另外也会放一些通用函数代码
transformOnce#
const seen = new WeakSet()
export const transformOnce: NodeTransform = (node, context) => {
if (node.type === NodeTypes.ELEMENT && findDir(node, 'once', true)) {
if (seen.has(node) || context.inVOnce) {
return
}
seen.add(node)
context.inVOnce = true
context.helper(SET_BLOCK_TRACKING)
return () => {
context.inVOnce = false
const cur = context.currentNode as ElementNode | IfNode | ForNode
if (cur.codegenNode) {
cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */)
}
}
}
}看名字就是用来处理.once修饰符的场景
- findDir:这个就不看代码了,就是用来找到该节点某个指令用的。
- inVOnce:这个参考inVPre。
- SET_BLOCK_TRACKING:setBlockTracking。
这个方法有些没头没脑的,没办法需要和runtime搭配才行。如果发现.once这个修饰符,就将setBlockTracking这个辅助函数放入helper中。注意这里把inVOnce置为true。
然后返回一个回调,这个回调会在traverseNode方法的最后执行,不用担心isVOnce标志位被置为false,在执行的这个回调的时候子节点已经递归处理完毕了。
- cache方法来细嗦下
cache(exp, isVNode = false) {
return createCacheExpression(context.cached++, exp, isVNode)
}
export function createCacheExpression(
index: number,
value: JSChildNode,
isVNode: boolean = false
): CacheExpression {
return {
type: NodeTypes.JS_CACHE_EXPRESSION,
index,
value,
isVNode,
loc: locStub
}
}返回一个节点,类型是JS_CACHE_EXPRESSION
这个节点会作为当前节点的codegenNode, 注意这里的curr指的是当前的节点,也不用担心被切换到其它子节点去了,前面强调了很多次回调执行的时间,这个时候context.currentNode已经确保指回当前的节点了。
transformIf#
createStructuralDirectiveTransform(
/^(if|else|else-if)$/,
(node, dir, context) => {
return processIf(node, dir, context, (ifNode, branch, isRoot) => {
// #1587: We need to dynamically increment the key based on the current
// node's sibling nodes, since chained v-if/else branches are
// rendered at the same depth
const siblings = context.parent!.children
let i = siblings.indexOf(ifNode)
let key = 0
while (i-- >= 0) {
const sibling = siblings[i]
if (sibling && sibling.type === NodeTypes.IF) {
key += sibling.branches.length
}
}
// Exit callback. Complete the codegenNode when all children have been
// transformed.
return () => {
if (isRoot) {
ifNode.codegenNode = createCodegenNodeForBranch(
branch,
key,
context
) as IfConditionalExpression
} else {
// attach this branch's codegen node to the v-if root.
const parentCondition = getParentCondition(ifNode.codegenNode!)
parentCondition.alternate = createCodegenNodeForBranch(
branch,
key + ifNode.branches.length - 1,
context
)
}
}
})
}
)transformIf是一个高阶函数,通过传入一个函数给一个函数并最终返回一个函数。
- createStructuralDirectiveTransform这个方法下面单独开了个小标题分析了,作为一个高阶函数,返回一个封装了的函数。
在这里这个返回的函数就是transformIf。
我们传入的正则是/^(if|else|else-if)$/,表示如果prop匹配到if分支就命中这个传入的回调。
- processIf
export function processIf(
node: ElementNode,
dir: DirectiveNode,
context: TransformContext,
processCodegen?: (
node: IfNode,
branch: IfBranchNode,
isRoot: boolean
) => (() => void) | undefined
) {
if (
dir.name !== 'else' &&
(!dir.exp || !(dir.exp as SimpleExpressionNode).content.trim())
) {
const loc = dir.exp ? dir.exp.loc : node.loc
context.onError(
createCompilerError(ErrorCodes.X_V_IF_NO_EXPRESSION, dir.loc)
)
dir.exp = createSimpleExpression(`true`, false, loc)
}
if (!__BROWSER__ && context.prefixIdentifiers && dir.exp) {
// dir.exp can only be simple expression because vIf transform is applied
// before expression transform.
dir.exp = processExpression(dir.exp as SimpleExpressionNode, context)
}
if (__DEV__ && __BROWSER__ && dir.exp) {
validateBrowserExpression(dir.exp as SimpleExpressionNode, context)
}
if (dir.name === 'if') {
const branch = createIfBranch(node, dir)
const ifNode: IfNode = {
type: NodeTypes.IF,
loc: node.loc,
branches: [branch]
}
context.replaceNode(ifNode)
if (processCodegen) {
return processCodegen(ifNode, branch, true)
}
} else {
// locate the adjacent v-if
const siblings = context.parent!.children
const comments = []
let i = siblings.indexOf(node)
while (i-- >= -1) {
const sibling = siblings[i]
if (__DEV__ && sibling && sibling.type === NodeTypes.COMMENT) {
context.removeNode(sibling)
comments.unshift(sibling)
continue
}
if (
sibling &&
sibling.type === NodeTypes.TEXT &&
!sibling.content.trim().length
) {
context.removeNode(sibling)
continue
}
if (sibling && sibling.type === NodeTypes.IF) {
// Check if v-else was followed by v-else-if
if (
dir.name === 'else-if' &&
sibling.branches[sibling.branches.length - 1].condition === undefined
) {
context.onError(
createCompilerError(ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, node.loc)
)
}
// move the node to the if node's branches
context.removeNode()
const branch = createIfBranch(node, dir)
if (
__DEV__ &&
comments.length &&
// #3619 ignore comments if the v-if is direct child of <transition>
!(
context.parent &&
context.parent.type === NodeTypes.ELEMENT &&
isBuiltInType(context.parent.tag, 'transition')
)
) {
branch.children = [...comments, ...branch.children]
}
// check if user is forcing same key on different branches
if (__DEV__ || !__BROWSER__) {
const key = branch.userKey
if (key) {
sibling.branches.forEach(({ userKey }) => {
if (isSameKey(userKey, key)) {
context.onError(
createCompilerError(
ErrorCodes.X_V_IF_SAME_KEY,
branch.userKey!.loc
)
)
}
})
}
}
sibling.branches.push(branch)
const onExit = processCodegen && processCodegen(sibling, branch, false)
// since the branch was removed, it will not be traversed.
// make sure to traverse here.
traverseNode(branch, context)
// call on exit
if (onExit) onExit()
// make sure to reset currentNode after traversal to indicate this
// node has been removed.
context.currentNode = null
} else {
context.onError(
createCompilerError(ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, node.loc)
)
}
break
}
}
}代码过长。。。现在有些后悔不拆分为几个主题分几篇文章写了。。。。
跑题了,回到代码中。
这货也是接受一个函数作为参数,不过它并没有返回一个函数,不过很不巧的是它的这个函数参数返回了一个函数,所以这货本质也是一个高阶函数。
而这个函数参数返回的函数最终是作为createStructuralDirectiveTransform这个方法收集到的方法并返回给traverseNode方法中。
这中间有好几层套娃,在开始分析这个函数和它的参数之前,我们来缕清这之间的套娃关系。
直接画图吧。。。。

那么在理解这些函数之间的关系之后我们再回来分析代码就会简单很多。
回到processIf代码中
- dir.name:为啥这里会是else而不是v-else呢?上篇文章中讲过,在parse的过程中把v-xxx、:xxx以及@都处理掉了,v-xxx会变成xxx,:会变成bind 而@会变成on等。
- dir.arg:这个之前分析compiler-dom的时候也有说过,比如v-bind:xxx="aaa",这个xxx就是这个dir.arg,而这个aaa则是dir.exp。
- createIfBranch:来看下代码
function createIfBranch(node: ElementNode, dir: DirectiveNode): IfBranchNode {
const isTemplateIf = node.tagType === ElementTypes.TEMPLATE
return {
type: NodeTypes.IF_BRANCH,
loc: node.loc,
condition: dir.name === 'else' ? undefined : dir.exp,
children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
userKey: findProp(node, `key`),
isTemplateIf
}
}这个时候的tagType == TEMPLATE就派上用场了,之前parse过滤TEMPLATE的时候是不会过滤IF/FOR/SLOT等场景的。
创建了一个IF_BRANCH类型的节点
而findProp就不看了,就是用来找它的某个静态属性的,在这里用来找key
回到processIf中
如果不是v-else的if指令但是没有表达式,直接报错。老规矩报错的代码咱就不看了。
接着如果context.prefixIdentifiers是true并且这个if指令有表达式也就是exp的话就提前处理这个表达式,为什么是提前呢?因为if指令的处理是在表达式的处理之前

接着如果是v-if指令则创建一个IF_BRANCH类型的节点,而这个branch节点则作为这个IF节点的子节点。
- context.replaceNode我们来嗦下,代码就不贴出来了,就是将context.currentNode以及parent.children[index]也就是节点当前的位置替换成另一个节点,这也就是为什么之后traverseNode之后需要把context.currentNode重置回去的原因,这中间有可能存在被删除/替换等问题。
- processCodegen:就是processIf接收的回调,这里先不看那块代码,先继续往下分析。
如果不是v-if指令,那就有可能是v-else以及v-else-if。
在处理v-else/else-if之前,还需要处理这个v-else/else-if节点之前的注释节点,都给它们移除先,为什么要这么做呢?因为if branch需要搭配注释节点,如果if条件是false,那么它就会被一个注释节点替代,当它变成true的时候它又会替换回来,当然你的注释都给你留着,不会做删掉你代码的行为的。另外没有用的节点也都去掉,比如空文本节点。
接着是判断这个else-if/else的节点之前是否存在v-if或者v-else-if节点,为什么要这么做呢?因为v-if和v-else-if/else之间是没有联系的,在ast中它们就是独立的节点。所以这个时候发现这是个v-else-if/v-else的节点之后,它得先回去看下是否存在v-if/v-else-if分支才行。
注意这里判断的时候是判断前一个节点里的branches的最后一个节点,为什么呢?因为如果这是个符合要求的if branch,那么它就会被移动到node.branches里面去,这样就能建立联系了。
这里还有一个fix,当transition组件里的第一个节点使用if指令的话,就得忽略掉全部注释,具体原因可以看注释里的issue。除transition之外的就把注释节点放到它的children里面,也就是说原本和注释同级的关系,现在变成了父子关系,这样也保留了注释的位置。
这里还有一个对key属性的处理,你有可能把for block的标志位key放到了一个if branch节点上,如果每个节点都一样的话是有问题的,因为vue会尽可能的复用每一个dom,如果你这俩key一样,当条件变了之后,这个节点和它的子节点们会被会复用,那么你这个if条件就有问题了,当然,如果tag不同应该是可以避免这个问题的。
最后再执行传入的回调,当然同时还得traverseNode一遍这个节点的子节点,为什么呢?因为这个if节点已经被移动到IF类型的节点的 branches里面去了,所以它的子节点不手动调用traverseNode的话是不会被遍历处理的。
注意最后这里把原来应该返回出去的回调给执行了,这个点和v-if分支的不同。

接下来我们来看下这个回调做了什么。
这个函数的调用位置是在节点被移除之后。
(ifNode, branch, isRoot) => {
// #1587: We need to dynamically increment the key based on the current
// node's sibling nodes, since chained v-if/else branches are
// rendered at the same depth
const siblings = context.parent!.children
let i = siblings.indexOf(ifNode)
let key = 0
while (i-- >= 0) {
const sibling = siblings[i]
if (sibling && sibling.type === NodeTypes.IF) {
key += sibling.branches.length
}
}
// Exit callback. Complete the codegenNode when all children have been
// transformed.
return () => {
if (isRoot) {
ifNode.codegenNode = createCodegenNodeForBranch(
branch,
key,
context
) as IfConditionalExpression
} else {
// attach this branch's codegen node to the v-if root.
const parentCondition = getParentCondition(ifNode.codegenNode!)
parentCondition.alternate = createCodegenNodeForBranch(
branch,
key + ifNode.branches.length - 1,
context
)
}
}
}- createCodegenNodeForBranch:
function createCodegenNodeForBranch(
branch: IfBranchNode,
keyIndex: number,
context: TransformContext
): IfConditionalExpression | BlockCodegenNode | MemoExpression {
if (branch.condition) {
return createConditionalExpression(
branch.condition,
createChildrenCodegenNode(branch, keyIndex, context),
// make sure to pass in asBlock: true so that the comment node call
// closes the current block.
createCallExpression(context.helper(CREATE_COMMENT), [
__DEV__ ? '"v-if"' : '""',
'true'
])
) as IfConditionalExpression
} else {
return createChildrenCodegenNode(branch, keyIndex, context)
}
}
function createChildrenCodegenNode(
branch: IfBranchNode,
keyIndex: number,
context: TransformContext
): BlockCodegenNode | MemoExpression {
const { helper } = context
const keyProperty = createObjectProperty(
`key`,
createSimpleExpression(
`${keyIndex}`,
false,
locStub,
ConstantTypes.CAN_HOIST
)
)
const { children } = branch
const firstChild = children[0]
const needFragmentWrapper =
children.length !== 1 || firstChild.type !== NodeTypes.ELEMENT
if (needFragmentWrapper) {
if (children.length === 1 && firstChild.type === NodeTypes.FOR) {
// optimize away nested fragments when child is a ForNode
const vnodeCall = firstChild.codegenNode!
injectProp(vnodeCall, keyProperty, context)
return vnodeCall
} else {
let patchFlag = PatchFlags.STABLE_FRAGMENT
let patchFlagText = PatchFlagNames[PatchFlags.STABLE_FRAGMENT]
// check if the fragment actually contains a single valid child with
// the rest being comments
if (
__DEV__ &&
!branch.isTemplateIf &&
children.filter(c => c.type !== NodeTypes.COMMENT).length === 1
) {
patchFlag |= PatchFlags.DEV_ROOT_FRAGMENT
patchFlagText += `, ${PatchFlagNames[PatchFlags.DEV_ROOT_FRAGMENT]}`
}
return createVNodeCall(
context,
helper(FRAGMENT),
createObjectExpression([keyProperty]),
children,
patchFlag + (__DEV__ ? ` /* ${patchFlagText} */` : ``),
undefined,
undefined,
true,
false,
false /* isComponent */,
branch.loc
)
}
} else {
const ret = (firstChild as ElementNode).codegenNode as
| BlockCodegenNode
| MemoExpression
const vnodeCall = getMemoedVNodeCall(ret)
// Change createVNode to createBlock.
if (vnodeCall.type === NodeTypes.VNODE_CALL) {
makeBlock(vnodeCall, context)
}
// inject branch key
injectProp(vnodeCall, keyProperty, context)
return ret
}
}看上面的图,这个函数中返回的回调是在traverseNode函数的最后调用的,这就意味着这个时候的ast节点们都已经有了codegenNode了,也就是经过nodeTransforms里注册的插件们的摧残了。
开始先是找到这个IF_BRANCH节点的父节点也就是IF类型的节点的位置,然后把它之前的IF节点的IF_BRANCH分支的节点的个数都加起来作为这个IF类型的节点包括它branch分支里的IF_BRANCH节点的key值,为什么要这么做呢?我们先往下看。
- condition:是经过加工处理后的exp,还记得我们强调了好几次的回调执行位置吗?它是在节点被nodeTransforms里的插件们都折磨之后才执行的,所以这个时候自然也执行过了transformExpression这个插件,所以dir.exp在if指令的场景下变成了condition这个字段。
- CREATE_COMMENT:辅助函数createCommentVNode,看到没,果然和注释节点勾搭上了。
- createCallExpression:创建一个函数调用节点,返回一个JS_CALL_EXPRESSION类型的节点,注意这个节点是在codegen之后才会有的,callee是上面的createCommentVNode辅助函数。
- createObjectProperty:这个就不看代码了,返回一个对象属性表达式,也就是{ xx: aa }的xx: aa节点
- createSimpleExpression:这个也不看代码了,就是创建一个单一表达式节点作为上面对象属性节点的value,它的content就是之前遍历keyIndex也就是当前if分支的第几个。
- createChildrenCodegenNode这个方法很明显是用来给branch自身创建codegenNode的。
- injectProp:这个方法一看就是用来把prop注入到某个子节点里的。这个方法里做了什么我们先不看了。。又是一个上百行的函数。
注意这个createChildrenCodegenNode处理的是这个branch的children也就是子节点而不是branches。
还记得之前说过的v-if/v-for等都是会创建一个block的,这里显然就是创建一个block,如果这个branch的子节点(注意是子节点而不是所有子孙节点)不止一个,那就得创建一个fragement来包裹它们,当然,如果第一个节点不是ELEMENT的话那也得用fragement包裹它们,因为它可能是FOR等会创建一个block的类型。
如果节点数只有一个并且第一个子节点是FOR类型的,那直接复用同一个fragement就行了。但是如果节点数不止一个,也就是说在FOR节点下面还跟着一些同级节点,这个时候自然就不能复用同一个fragement了,自然需要重新创建一个fragement。
现在我们再来看下这个injectProp。
export function injectProp(
node: VNodeCall | RenderSlotCall,
prop: Property,
context: TransformContext
) {
let propsWithInjection: ObjectExpression | CallExpression | undefined
/**
* 1. mergeProps(...)
* 2. toHandlers(...)
* 3. normalizeProps(...)
* 4. normalizeProps(guardReactiveProps(...))
*
* we need to get the real props before normalization
*/
let props =
node.type === NodeTypes.VNODE_CALL ? node.props : node.arguments[2]
let callPath: CallExpression[] = []
let parentCall: CallExpression | undefined
if (
props &&
!isString(props) &&
props.type === NodeTypes.JS_CALL_EXPRESSION
) {
const ret = getUnnormalizedProps(props)
props = ret[0]
callPath = ret[1]
parentCall = callPath[callPath.length - 1]
}
if (props == null || isString(props)) {
propsWithInjection = createObjectExpression([prop])
} else if (props.type === NodeTypes.JS_CALL_EXPRESSION) {
// merged props... add ours
// only inject key to object literal if it's the first argument so that
// if doesn't override user provided keys
const first = props.arguments[0] as string | JSChildNode
if (!isString(first) && first.type === NodeTypes.JS_OBJECT_EXPRESSION) {
first.properties.unshift(prop)
} else {
if (props.callee === TO_HANDLERS) {
// #2366
propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
createObjectExpression([prop]),
props
])
} else {
props.arguments.unshift(createObjectExpression([prop]))
}
}
!propsWithInjection && (propsWithInjection = props)
} else if (props.type === NodeTypes.JS_OBJECT_EXPRESSION) {
let alreadyExists = false
// check existing key to avoid overriding user provided keys
if (prop.key.type === NodeTypes.SIMPLE_EXPRESSION) {
const propKeyName = prop.key.content
alreadyExists = props.properties.some(
p =>
p.key.type === NodeTypes.SIMPLE_EXPRESSION &&
p.key.content === propKeyName
)
}
if (!alreadyExists) {
props.properties.unshift(prop)
}
propsWithInjection = props
} else {
// single v-bind with expression, return a merged replacement
propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
createObjectExpression([prop]),
props
])
// in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
// it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
// the `guardReactiveProps` will no longer be needed
if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
parentCall = callPath[callPath.length - 2]
}
}
if (node.type === NodeTypes.VNODE_CALL) {
if (parentCall) {
parentCall.arguments[0] = propsWithInjection
} else {
node.props = propsWithInjection
}
} else {
if (parentCall) {
parentCall.arguments[0] = propsWithInjection
} else {
node.arguments[2] = propsWithInjection
}
}
}这个方法一看就是用来将其中一个节点的属性注入到另一个节点里面
- getUnnormalizedProps:这个方法的代码我们就不看了,简单地说就是如果你这个props是一个JS_CALL_EXPRESSION,那么就会递归找这个callee的arguments[0],看是否是规范的并且存储这个prop的递归路径最后返回这个prop和callPath。
- createObjectExpression:这个方法的代码我们也不看了,就是创建一个js对象节点,prop是上面创建的对象属性节点,key是key,value是上面获取到的keyIndex,现在合并到这个对象节点中,注意这个对象节点是一个字面量节点,比如prop="{ a: 123 }",这个{ a: 123 }就是一个字面量对象。
- createCallExpression:不多说。
由于这个方法中的场景我们并不清楚,比如这个props出现的条件,我这里思考的几种场景比如for的目标是一个scope variable等都是undefined,所以我这里也只能简单的猜测下发生了什么事。
-
首先是获取对应需要合并的属性
-
注入属性:
- 如果props是一个函数调用节点,那么就注入到这个节点的第一个参数中,前提是这个参数是一个对象字面量。
- 如果props是一个函数调用节点,它的callee是一个名为toHandlers的辅助函数,这个时候就需要创建一个新的节点并加入辅助函数mergeProps,这样做可以避免覆盖该注入节点原有的key属性。
- 如果这个节点的props自身就是一个对象字面量,那么这个就判断是否存在key这个属性,没有就加上,有就算逑。
- 剩余的场景也是直接同上第二点,如果遇到了嵌套辅助函数调用,比如normalizeProps(guardReactiveProps(props)),会被重写为normalizeProps(mergeProps({ key: 0 }, props))。
那么这个指令的处理我们终于分析完了,我们来简单的总结下
- 将所有的IF_BRANCH节点关联起来(指同一if逻辑块的,并非全部,同层节点可能存在多个if逻辑块),move到一个IF类型的节点的branch中。注意这里是move而不是copy。
- 给这个IF_BRANCH节点生成codegenNode节点。
- 给这个IF节点生成codegenNode节点。
最后来看下render function

补充: 1. 貌似这个keyIndex是用来干啥的还是不清楚,其实这个key是每个节点都会有的,到时候runtime的diff操作就需要这个key来判断是否需要re-render。而这个key代表着这个节点的位置。
transformMemo#
在看代码之前,我们先来看下/熟悉下v-memo的用处 Built-in Directives | Vue.js (vuejs.org)
const seen = new WeakSet()
export const transformMemo: NodeTransform = (node, context) => {
if (node.type === NodeTypes.ELEMENT) {
const dir = findDir(node, 'memo')
if (!dir || seen.has(node)) {
return
}
seen.add(node)
return () => {
const codegenNode =
node.codegenNode ||
(context.currentNode as PlainElementNode).codegenNode
if (codegenNode && codegenNode.type === NodeTypes.VNODE_CALL) {
// non-component sub tree should be turned into a block
if (node.tagType !== ElementTypes.COMPONENT) {
makeBlock(codegenNode, context)
}
node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
dir.exp!,
createFunctionExpression(undefined, codegenNode),
`_cache`,
String(context.cached++)
]) as MemoExpression
}
}
}
}
export function createFunctionExpression(
params: FunctionExpression['params'],
returns: FunctionExpression['returns'] = undefined,
newline: boolean = false,
isSlot: boolean = false,
loc: SourceLocation = locStub
): FunctionExpression {
return {
type: NodeTypes.JS_FUNCTION_EXPRESSION,
params,
returns,
newline,
isSlot,
loc
}
}这个方法的逻辑没啥好说的,就是创建一个函数调用表达式节点,辅助函数是withMemo。直接来看render function舒服一点

没啥好说的,就是做了cache缓存处理
transformFor#
transformFor的执行流程和v-if类似的,所以图我就不放了,参考transformIf里的即可。
既然是类似的,我这里就不放代码了,到时候接触到再放出来。
我们先来看下processFor的代码
export function processFor(
node: ElementNode,
dir: DirectiveNode,
context: TransformContext,
processCodegen?: (forNode: ForNode) => (() => void) | undefined
) {
// ...省略错误场景
const parseResult = parseForExpression(
// can only be simple expression because vFor transform is applied
// before expression transform.
dir.exp as SimpleExpressionNode,
context
)
// ...省略错误场景
const { addIdentifiers, removeIdentifiers, scopes } = context
const { source, value, key, index } = parseResult
const forNode: ForNode = {
type: NodeTypes.FOR,
loc: dir.loc,
source,
valueAlias: value,
keyAlias: key,
objectIndexAlias: index,
parseResult,
children: isTemplateNode(node) ? node.children : [node]
}
context.replaceNode(forNode)
// bookkeeping
scopes.vFor++
if (!__BROWSER__ && context.prefixIdentifiers) {
// scope management
// inject identifiers to context
value && addIdentifiers(value)
key && addIdentifiers(key)
index && addIdentifiers(index)
}
const onExit = processCodegen && processCodegen(forNode)
return () => {
scopes.vFor--
if (!__BROWSER__ && context.prefixIdentifiers) {
value && removeIdentifiers(value)
key && removeIdentifiers(key)
index && removeIdentifiers(index)
}
if (onExit) onExit()
}
}- parseForExpression:想了下,还是不要看代码了,后面的其他函数的也一样,由于没有拆成几篇文章来写,现在有些太大了,控制不住。。。。简单的说就是处理v-for="xx"的xx。我们直接来看下数据

不过有几个地方需要注意。
- 正则,这个正则可能有公司笔试题会出,貌似阿里就出过手写解析v-for的笔试题。
/([\s\S]?)\s+(?:in|of)\s+([\s\S])/

- 获取(xx, index) in/of aaaa里的()里的内容的表达式:/^(|)$/g。

- 匹配这个()里的数据的index/key正则:/,([^,}]])(?:,([^,}]]))?$/。

当迭代的是一个object,那么你可以传入三个参数,比如
。回到processFor里面
- addIdentifiers:这个方法这里就不贴代码了,代码在createTransformContext方法里。简单的说就是将这个变量也就是indetifier存放到context里面,如果已经有了就自加。
- removeIdentifiers:同上,把这个identifier从这个context中移除。
这俩方法是用来处理scope variable的,当进入这个block的scope的时候就add,当出了就remove。
- replaceNode:这个之前说过了,这里再简单说下,将context.currentNode替换成当前的node。
- scopes:之前有说过,就是会生成scope的几个指令的个数记录

简单的说下这个processFor方法,重点是parseForExpression,解析出for表达式的数据,然后将它们add到context里的,因为从这里开始已经进入了for的scope里。然后执行回调参数,返回一个函数,这个函数也是和processIf的一样,返回的这个回调会在这个节点被处理完之后再执行,所以这个时候已经退出scope了,自然就得将它们remove。
那么现在来看下传入processFor的回调
在这之前,需要注意的一点是这个函数参数执行的位置并不在processFor的返回函数中,所以它的执行是在transformFor这个插件的处理过程中就执行的。
forNode => {
// create the loop render function expression now, and add the
// iterator on exit after all children have been traversed
const renderExp = createCallExpression(helper(RENDER_LIST), [
forNode.source
]) as ForRenderListExpression
const isTemplate = isTemplateNode(node)
const memo = findDir(node, 'memo')
const keyProp = findProp(node, `key`)
const keyExp =
keyProp &&
(keyProp.type === NodeTypes.ATTRIBUTE
? createSimpleExpression(keyProp.value!.content, true)
: keyProp.exp!)
const keyProperty = keyProp ? createObjectProperty(`key`, keyExp!) : null
if (!__BROWSER__ && isTemplate) {
// #2085 / #5288 process :key and v-memo expressions need to be
// processed on `<template v-for>`. In this case the node is discarded
// and never traversed so its binding expressions won't be processed
// by the normal transforms.
if (memo) {
memo.exp = processExpression(
memo.exp! as SimpleExpressionNode,
context
)
}
if (keyProperty && keyProp!.type !== NodeTypes.ATTRIBUTE) {
keyProperty.value = processExpression(
keyProperty.value as SimpleExpressionNode,
context
)
}
}
const isStableFragment =
forNode.source.type === NodeTypes.SIMPLE_EXPRESSION &&
forNode.source.constType > ConstantTypes.NOT_CONSTANT
const fragmentFlag = isStableFragment
? PatchFlags.STABLE_FRAGMENT
: keyProp
? PatchFlags.KEYED_FRAGMENT
: PatchFlags.UNKEYED_FRAGMENT
forNode.codegenNode = createVNodeCall(
context,
helper(FRAGMENT),
undefined,
renderExp,
fragmentFlag +
(__DEV__ ? ` /* ${PatchFlagNames[fragmentFlag]} */` : ``),
undefined,
undefined,
true /* isBlock */,
!isStableFragment /* disableTracking */,
false /* isComponent */,
node.loc
) as ForCodegenNode
return () => {
// finish the codegen now that all children have been traversed
let childBlock: BlockCodegenNode
const { children } = forNode
// check <template v-for> key placement
// ...省略 template搭配`key`的错误场景
const needFragmentWrapper =
children.length !== 1 || children[0].type !== NodeTypes.ELEMENT
const slotOutlet = isSlotOutlet(node)
? node
: isTemplate &&
node.children.length === 1 &&
isSlotOutlet(node.children[0])
? (node.children[0] as SlotOutletNode) // api-extractor somehow fails to infer this
: null
if (slotOutlet) {
// <slot v-for="..."> or <template v-for="..."><slot/></template>
childBlock = slotOutlet.codegenNode as RenderSlotCall
if (isTemplate && keyProperty) {
// <template v-for="..." :key="..."><slot/></template>
// we need to inject the key to the renderSlot() call.
// the props for renderSlot is passed as the 3rd argument.
injectProp(childBlock, keyProperty, context)
}
} else if (needFragmentWrapper) {
// <template v-for="..."> with text or multi-elements
// should generate a fragment block for each loop
childBlock = createVNodeCall(
context,
helper(FRAGMENT),
keyProperty ? createObjectExpression([keyProperty]) : undefined,
node.children,
PatchFlags.STABLE_FRAGMENT +
(__DEV__
? ` /* ${PatchFlagNames[PatchFlags.STABLE_FRAGMENT]} */`
: ``),
undefined,
undefined,
true,
undefined,
false /* isComponent */
)
} else {
// Normal element v-for. Directly use the child's codegenNode
// but mark it as a block.
childBlock = (children[0] as PlainElementNode)
.codegenNode as VNodeCall
if (isTemplate && keyProperty) {
injectProp(childBlock, keyProperty, context)
}
if (childBlock.isBlock !== !isStableFragment) {
if (childBlock.isBlock) {
// switch from block to vnode
removeHelper(OPEN_BLOCK)
removeHelper(
getVNodeBlockHelper(context.inSSR, childBlock.isComponent)
)
} else {
// switch from vnode to block
removeHelper(
getVNodeHelper(context.inSSR, childBlock.isComponent)
)
}
}
childBlock.isBlock = !isStableFragment
if (childBlock.isBlock) {
helper(OPEN_BLOCK)
helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent))
} else {
helper(getVNodeHelper(context.inSSR, childBlock.isComponent))
}
}
if (memo) {
const loop = createFunctionExpression(
createForLoopParams(forNode.parseResult, [
createSimpleExpression(`_cached`)
])
)
loop.body = createBlockStatement([
createCompoundExpression([`const _memo = (`, memo.exp!, `)`]),
createCompoundExpression([
`if (_cached`,
...(keyExp ? [` && _cached.key === `, keyExp] : []),
` && ${context.helperString(
IS_MEMO_SAME
)}(_cached, _memo)) return _cached`
]),
createCompoundExpression([`const _item = `, childBlock as any]),
createSimpleExpression(`_item.memo = _memo`),
createSimpleExpression(`return _item`)
])
renderExp.arguments.push(
loop as ForIteratorExpression,
createSimpleExpression(`_cache`),
createSimpleExpression(String(context.cached++))
)
} else {
renderExp.arguments.push(
createFunctionExpression(
createForLoopParams(forNode.parseResult),
childBlock,
true /* force newline */
) as ForIteratorExpression
)
}
}
}- isStableFragement:v-for="xxx"中的这个xxx就是source,如果不是http://ctx.xxx,那就是stable。
- fragementFlag:也就是即将创建的fragement的nodeflag,前面说过这里的v-for也是会创建fragement的。
这里有个地方需要注意:前面说了这个函数参数是在插件执行过程中执行的,但是这个函数参数的返回函数却是在所有插件执行之后才执行的,也就是过了codegen阶段。
- isSlotOut:这个方法是确定这个节点是否用了slot,比如或者这两种情况都是。
- injectProp:这个方法上面有分析了,这里再简单说下就是将父节点的属性注入到子节点里。在这里则是场景中将template的属性注入到slot里。
- createForLoopParams:代码就不看了,简单地说就是创建一个params数组,囊括for的key、index、value以及memo自己就有的_cache,而这些params将作为renderList的参数。
- renderExp:这个就是renderList的函数调用表达式。
简单的总结下:
这个函数参数中实际上是在创建v-for的codegenNode。
有几个特殊场景需要说下:
- 搭配的场景需要注入给
- 如果for包裹的子节点存在多个,那就需要创建fragement
- 如果非上面的场景,那就是常规场景:
- 如果这个v-for="xxx"的xxx是稳定的(等级高于NOT_CONSTANT)单一表达式节点,那么就创建VNode
- 而如果等级是NOT_CONSTANT,那么就是创建一个block。
另外这里还有兼容v-memo的场景。最后生成的render function其实前面分析v-memo的时候你已经看过了,这里再贴一次。

补充:vForNode搭配的辅助函数是renderList
transformFilter#
因为篇幅和兼容性问题(filter在3.x中废弃),这里咱就不分析了,感兴趣的大佬可以自行去了解
trackVForSlotScopes#
这个插件处理的场景比较特殊
先来看下/复习下这个v-slot属性 Built-in Directives | Vue.js (vuejs.org)
然后我们来复现下场景
这个场景需要一个for和v-slot同时存在一个template节点上
<Add :my-prop="index">
<template v-for="(item, index) in tt" :key="item" v-slot:default>
<div @click="handle">
</div>
</template>
</Add>- parseForExpression:这个我们前面说过了是用来解析v-for的表达式的。
这个插件很简单,就是这个特殊场景给它加上scope variable。
在出scope的时候再移除这些scope variable。具体为啥要这么做呢?我们后面分析vSlot的时候会分析到,这里先mark下。

transformExpression#
export const transformExpression: NodeTransform = (node, context) => {
if (node.type === NodeTypes.INTERPOLATION) {
node.content = processExpression(
node.content as SimpleExpressionNode,
context
)
} else if (node.type === NodeTypes.ELEMENT) {
// handle directives on element
for (let i = 0; i < node.props.length; i++) {
const dir = node.props[i]
// do not process for v-on & v-for since they are special handled
if (dir.type === NodeTypes.DIRECTIVE && dir.name !== 'for') {
const exp = dir.exp
const arg = dir.arg
// do not process exp if this is v-on:arg - we need special handling
// for wrapping inline statements.
if (
exp &&
exp.type === NodeTypes.SIMPLE_EXPRESSION &&
!(dir.name === 'on' && arg)
) {
dir.exp = processExpression(
exp,
context,
// slot args must be processed as function params
dir.name === 'slot'
)
}
if (arg && arg.type === NodeTypes.SIMPLE_EXPRESSION && !arg.isStatic) {
dir.arg = processExpression(arg, context)
}
}
}
}
}- processExpression:这个方法里面有很多东西,之前分析compiler-dom指令那一章节的时候有具体分析,这里就不再分析了,简单地说就是把表达式转换成一个节点。对如何处理表达式的内容感兴趣的大佬可以看我之前的文章:vue/compiler-dom源码分析学习--day3: 转换指令 - 知乎 (zhihu.com)
这个方法也是相当的简单(不包括processExpression,它里面的东西很多很杂)
就是将这个节点的所有涉及到表达式的内容转换成节点,比如指令的表达式,{{}}语法中的表达式,其中v-on & v-for的场景需要额外插件处理,比较特殊。
这里需要注意的一点是slot的会被转换成一个函数参数节点。
transformSlotOutlet#
export const transformSlotOutlet: NodeTransform = (node, context) => {
if (isSlotOutlet(node)) {
const { children, loc } = node
const { slotName, slotProps } = processSlotOutlet(node, context)
const slotArgs: CallExpression['arguments'] = [
context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
slotName,
'{}',
'undefined',
'true'
]
let expectedLen = 2
if (slotProps) {
slotArgs[2] = slotProps
expectedLen = 3
}
if (children.length) {
slotArgs[3] = createFunctionExpression([], children, false, false, loc)
expectedLen = 4
}
if (context.scopeId && !context.slotted) {
expectedLen = 5
}
slotArgs.splice(expectedLen) // remove unused arguments
node.codegenNode = createCallExpression(
context.helper(RENDER_SLOT),
slotArgs,
loc
)
}
}- processSlotOutlet:我们先不看这个方法代码,这里看名字可以指导师在处理v-slot的表达式。
- RENDER_SLOT:renderSlot,slot tag搭配的辅助函数
注意这个slotoutlet处理的是而不是v-slot。
然后我们来看下processSlotOutlet的代码
export function processSlotOutlet(
node: SlotOutletNode,
context: TransformContext
): SlotOutletProcessResult {
let slotName: string | ExpressionNode = `"default"`
let slotProps: PropsExpression | undefined = undefined
const nonNameProps = []
for (let i = 0; i < node.props.length; i++) {
const p = node.props[i]
if (p.type === NodeTypes.ATTRIBUTE) {
if (p.value) {
if (p.name === 'name') {
slotName = JSON.stringify(p.value.content)
} else {
p.name = camelize(p.name)
nonNameProps.push(p)
}
}
} else {
if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
if (p.exp) slotName = p.exp
} else {
if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
p.arg.content = camelize(p.arg.content)
}
nonNameProps.push(p)
}
}
}
if (nonNameProps.length > 0) {
const { props, directives } = buildProps(
node,
context,
nonNameProps,
false,
false
)
slotProps = props
if (directives.length) {
context.onError(
createCompilerError(
ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET,
directives[0].loc
)
)
}
}
return {
slotName,
slotProps
}
}这个方法也没啥好说的,收集prop,找到name字段,然后返回。

transformElement#
这个插件是重点插件
// some directive transforms (e.g. v-model) may return a symbol for runtime
// import, which should be used instead of a resolveDirective call.
const directiveImportMap = new WeakMap<DirectiveNode, symbol>()
// generate a JavaScript AST for this element's codegen
export const transformElement: NodeTransform = (node, context) => {
// perform the work on exit, after all child expressions have been
// processed and merged.
return function postTransformElement() {
node = context.currentNode!
if (
!(
node.type === NodeTypes.ELEMENT &&
(node.tagType === ElementTypes.ELEMENT ||
node.tagType === ElementTypes.COMPONENT)
)
) {
return
}
const { tag, props } = node
const isComponent = node.tagType === ElementTypes.COMPONENT
// The goal of the transform is to create a codegenNode implementing the
// VNodeCall interface.
let vnodeTag = isComponent
? resolveComponentType(node as ComponentNode, context)
: `"${tag}"`
const isDynamicComponent =
isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT
let vnodeProps: VNodeCall['props']
let vnodeChildren: VNodeCall['children']
let vnodePatchFlag: VNodeCall['patchFlag']
let patchFlag: number = 0
let vnodeDynamicProps: VNodeCall['dynamicProps']
let dynamicPropNames: string[] | undefined
let vnodeDirectives: VNodeCall['directives']
let shouldUseBlock =
// dynamic component may resolve to plain elements
isDynamicComponent ||
vnodeTag === TELEPORT ||
vnodeTag === SUSPENSE ||
(!isComponent &&
// <svg> and <foreignObject> must be forced into blocks so that block
// updates inside get proper isSVG flag at runtime. (#639, #643)
// This is technically web-specific, but splitting the logic out of core
// leads to too much unnecessary complexity.
(tag === 'svg' || tag === 'foreignObject'))
// props
if (props.length > 0) {
const propsBuildResult = buildProps(
node,
context,
undefined,
isComponent,
isDynamicComponent
)
vnodeProps = propsBuildResult.props
patchFlag = propsBuildResult.patchFlag
dynamicPropNames = propsBuildResult.dynamicPropNames
const directives = propsBuildResult.directives
vnodeDirectives =
directives && directives.length
? (createArrayExpression(
directives.map(dir => buildDirectiveArgs(dir, context))
) as DirectiveArguments)
: undefined
if (propsBuildResult.shouldUseBlock) {
shouldUseBlock = true
}
}
// children
if (node.children.length > 0) {
if (vnodeTag === KEEP_ALIVE) {
// Although a built-in component, we compile KeepAlive with raw children
// instead of slot functions so that it can be used inside Transition
// or other Transition-wrapping HOCs.
// To ensure correct updates with block optimizations, we need to:
// 1. Force keep-alive into a block. This avoids its children being
// collected by a parent block.
shouldUseBlock = true
// 2. Force keep-alive to always be updated, since it uses raw children.
patchFlag |= PatchFlags.DYNAMIC_SLOTS
if (__DEV__ && node.children.length > 1) {
context.onError(
createCompilerError(ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN, {
start: node.children[0].loc.start,
end: node.children[node.children.length - 1].loc.end,
source: ''
})
)
}
}
const shouldBuildAsSlots =
isComponent &&
// Teleport is not a real component and has dedicated runtime handling
vnodeTag !== TELEPORT &&
// explained above.
vnodeTag !== KEEP_ALIVE
if (shouldBuildAsSlots) {
const { slots, hasDynamicSlots } = buildSlots(node, context)
vnodeChildren = slots
if (hasDynamicSlots) {
patchFlag |= PatchFlags.DYNAMIC_SLOTS
}
} else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
const child = node.children[0]
const type = child.type
// check for dynamic text children
const hasDynamicTextChild =
type === NodeTypes.INTERPOLATION ||
type === NodeTypes.COMPOUND_EXPRESSION
if (
hasDynamicTextChild &&
getConstantType(child, context) === ConstantTypes.NOT_CONSTANT
) {
patchFlag |= PatchFlags.TEXT
}
// pass directly if the only child is a text node
// (plain / interpolation / expression)
if (hasDynamicTextChild || type === NodeTypes.TEXT) {
vnodeChildren = child as TemplateTextChildNode
} else {
vnodeChildren = node.children
}
} else {
vnodeChildren = node.children
}
}
// patchFlag & dynamicPropNames
if (patchFlag !== 0) {
if (__DEV__) {
if (patchFlag < 0) {
// special flags (negative and mutually exclusive)
vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`
} else {
// bitwise flags
const flagNames = Object.keys(PatchFlagNames)
.map(Number)
.filter(n => n > 0 && patchFlag & n)
.map(n => PatchFlagNames[n])
.join(`, `)
vnodePatchFlag = patchFlag + ` /* ${flagNames} */`
}
} else {
vnodePatchFlag = String(patchFlag)
}
if (dynamicPropNames && dynamicPropNames.length) {
vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames)
}
}
node.codegenNode = createVNodeCall(
context,
vnodeTag,
vnodeProps,
vnodeChildren,
vnodePatchFlag,
vnodeDynamicProps,
vnodeDirectives,
!!shouldUseBlock,
false /* disableTracking */,
isComponent,
node.loc
)
}
}resolveComponentType:代码分析放下面,这里简单地说就是确定这个组件的具体类型,比如内置组件,自定义组件等。isDynamicComponent:是否是动态组件。shouldUseBlock:是否需要开启block包裹,如果是动态组件/TELEPORT/SUSPENSE以及svg/foreignObject这几种情况都是需要开启的。buildProps这个方法代码过长,所以这里不贴代码,分析也放到下面去,不然篇幅又不够了,这里简单地说就是处理节点的prop,给prop分门别类,比如directives、props等。这里的props就是之前我们埋的一个坑的来源。buildDirectiveArgs:这个方法也放到下面分析,看名字就知道是给directive的arg创建节点的。buildSlots:同buildProps。stringifyDynamicPropNames:这个方法也不看代码了,就是将动态的属性收集然后字符串化,比如'[xxxx, xxx]'createVNodeCall:这回我们倒是要看一下了,因为现在是codegenNode的核心
export function createVNodeCall(
context: TransformContext | null,
tag: VNodeCall['tag'],
props?: VNodeCall['props'],
children?: VNodeCall['children'],
patchFlag?: VNodeCall['patchFlag'],
dynamicProps?: VNodeCall['dynamicProps'],
directives?: VNodeCall['directives'],
isBlock: VNodeCall['isBlock'] = false,
disableTracking: VNodeCall['disableTracking'] = false,
isComponent: VNodeCall['isComponent'] = false,
loc = locStub
): VNodeCall {
if (context) {
if (isBlock) {
context.helper(OPEN_BLOCK)
context.helper(getVNodeBlockHelper(context.inSSR, isComponent))
} else {
context.helper(getVNodeHelper(context.inSSR, isComponent))
}
if (directives) {
context.helper(WITH_DIRECTIVES)
}
}
return {
type: NodeTypes.VNODE_CALL,
tag,
props,
children,
patchFlag,
dynamicProps,
directives,
isBlock,
disableTracking,
isComponent,
loc
}
}代码没什么内容,但是还是要贴出来,有个意识,知道它里面有哪些东西,这些东西代表着什么
这插件只处理元素和组件节点。
先是处理props,收集directives/dynamicPropNames/props(attribute)。
如果存在子节点,那么就有下面几种场景:
- 如果是组件并且组件存在子节点,那么这个组件就应该被视作一个
v-slot的节点。 - 不是上面的情况那就是元素节点,如果是只有一个子节点并且不是
teleport这个内置组件,那么就判断这个子节点是否是一个动态的文本节点({{}}或者复合表达式比如多个表达式之类的),如果确实是并且它的flag是NOT_CONSTANT,那么当前我们要处理的这个元素节点的flag就标记为PatchFlags.TEXT,这类型看注释是Indicates an element with dynamic textContent (children fast path)。也就是声明这个元素节点是一个带有动态文本内容的节点。 - 其他。
根据上面三种情况收集子节点。
然后收集这个节点的flag。
最后创建codegenNode
补充:
这里有一点需要注意,那就是这个transformElement插件的执行的时间点,它也是作为回调执行的,所以也是在节点被nodeTransforms里注册的插件遍历完之后再处理的,不过这个不是重点。
还记得之前我们说到过的这些回调的调用顺序是逆向的,就像是调用栈一样,所以transformElement插件的回调实际上执行的时间是比transformIf、transformFor早的,这也就是为什么那俩插件可以判断codegenNode了。
**resolveComponentType**
export function resolveComponentType(
node: ComponentNode,
context: TransformContext,
ssr = false
) {
let { tag } = node
// 1. dynamic component
const isExplicitDynamic = isComponentTag(tag)
const isProp = findProp(node, 'is')
if (isProp) {
if (
isExplicitDynamic ||
(__COMPAT__ &&
isCompatEnabled(
CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT,
context
))
) {
const exp =
isProp.type === NodeTypes.ATTRIBUTE
? isProp.value && createSimpleExpression(isProp.value.content, true)
: isProp.exp
if (exp) {
return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
exp
])
}
} else if (
isProp.type === NodeTypes.ATTRIBUTE &&
isProp.value!.content.startsWith('vue:')
) {
// <button is="vue:xxx">
// if not <component>, only is value that starts with "vue:" will be
// treated as component by the parse phase and reach here, unless it's
// compat mode where all is values are considered components
tag = isProp.value!.content.slice(4)
}
}
// 1.5 v-is (TODO: Deprecate)
const isDir = !isExplicitDynamic && findDir(node, 'is')
if (isDir && isDir.exp) {
return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
isDir.exp
])
}
// 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag)
if (builtIn) {
// built-ins are simply fallthroughs / have special handling during ssr
// so we don't need to import their runtime equivalents
if (!ssr) context.helper(builtIn)
return builtIn
}
// 3. user component (from setup bindings)
// this is skipped in browser build since browser builds do not perform
// binding analysis.
if (!__BROWSER__) {
const fromSetup = resolveSetupReference(tag, context)
if (fromSetup) {
return fromSetup
}
const dotIndex = tag.indexOf('.')
if (dotIndex > 0) {
const ns = resolveSetupReference(tag.slice(0, dotIndex), context)
if (ns) {
return ns + tag.slice(dotIndex)
}
}
}
// 4. Self referencing component (inferred from filename)
if (
!__BROWSER__ &&
context.selfName &&
capitalize(camelize(tag)) === context.selfName
) {
context.helper(RESOLVE_COMPONENT)
// codegen.ts has special check for __self postfix when generating
// component imports, which will pass additional `maybeSelfReference` flag
// to `resolveComponent`.
context.components.add(tag + `__self`)
return toValidAssetId(tag, `component`)
}
// 5. user component (resolve)
context.helper(RESOLVE_COMPONENT)
context.components.add(tag)
return toValidAssetId(tag, `component`)
} isComponentTag:不用看代码了,判断tag是否是component/Component。RESOLVE_DYNAMIC_COMPONENT:也就是辅助函数resolve_dynamic_component。
组件有以下几种场景
- 动态组件,动态组件有两种,一种是大家熟悉的
component tag搭配is属性;第二种则是3.x中支持的原生元素也可以用is属性,但是is属性的值的表达式要用vue:开头。 - 内置组件:
Teleport、Transition、KeepAlive、Suspense等。 - 开发者们自身的组件(
setup bindings应该是inline mode场景的,还有一个就是常规的) - 自引用组件,也就是自己引用自己
注意这里的内置组件代码中有一段if (!ssr) context.helper(builtIn),这也就是为什么我们不需要手动导入这些内置组件就能直接使用的原因。
resolveSetupReference:这个方法就不看了,是inline mode场景的。
buildProps
我这里说一下里面做了什么
- 处理
type == NodeTypes.ATTRIBUTE,也就是静态属性的场景:
- 如果是
ref并且是在v-for的scope里面的,这个时候就需要创建一个key的content为ref_for的对象属性节点,将它push到properties数组里。 - 如果这个属性是
is搭配tag为component或者它的exp是vue:开头的,那么它就是一个动态组件,应该跳过,因为这里是处理静态的。这里你应该会奇怪为什么这个的type是一个ATTRIBUTE,因为这个属性没有1用:或者v-bind开头,所以在最开始分配的时候就把它分配为静态的了。所以我们写代码的时候动态的就尽量用:或者v-bind,这样在parse阶段就可以分辨出来了。 - 其它的就都算是静态的了,即使你这个属性是不认识的
- 静态的结束了,就该轮到指令了
-
v-slot如果没有搭配component,那么直接报错v-slot can only be used on components or <template> tags.,然后跳过- 然后绕过
v-once/v-memo,因为已经有插件来处理它们了。 - 如果是动态的
key以及vue:before-update这俩,那就需要开启block - 动态的
ref在v-for的block里面也是得创建key的content为res_for的对象属性节点。 - 如果是
v-bind或者v-on,但是它没有arg节点,也就是v-on:xx="xxxx"的xx。实际上这是一种特殊的写法,v-bind的exp是一个对象,这个时候是可以的,比如:v-bind="{ key: 123 }"。在2.x的时候,这种方式是不会覆盖原来已有属性的,而3.x则相反,后面的会覆盖前面的。具体请看:v-bind Merge Behavior | Vue 3 Migration Guide (vuejs.org)。而v-on也是可以传入对象来绑定事件的,会创建一个JS_CALL_EXPRESSION的节点,辅助函数是toHandlers,这个方法是不是很眼熟?其实我们之前分析injectProp也就是注入属性的时候,就遇到了这个问题。结合当时分析的内容,我们可以确定这里的props以及toHandlers就是上边遇到的那俩。由于我们是动态传入一个对象,所以这个对象只能是在runtime的时候才能知道是什么东西,所以合并属性的过程自然就只能在runtime阶段。这也就是为什么需要再包裹一层mergeProps的辅助函数。 - 然后调用
context.directiveTransforms里注册的插件来处理这些指令,这里就暂时不分析插件里做了什么,我们继续先往下看。然后收集这些处理之后的指令。 - 如果是自定义指令,那么直接放到
runtimeDirectives中,因为编译器压根不知道是啥,得等到runtime阶段才知道,并且为了安全,直接开block,避免有涉及到before-update的调用相关的。
如果存在v-bind="object"/v-on="object"的就合并props,当然是在runtime阶段,辅助函数是mergeProps。
接着是根据这些个属性/指令等来进一步确定这个节点的flag:
- 如果有使用
v-bind/on="object",那么就当做FULL_PROPS,来看下这个类型的注释When keys change, a full diff is always needed to remove the old key.,也就是说patch阶段没办法绕过它的属性,diff需要全量。另外它和CLASS、PROPS、STYLE互斥。 - 没有动态
key:1. 不是组件但是有动态class绑定,这个时候flag类型是CLASS;2. 不是组件但是有动态样式绑定,flag为STYLE,这个类型有部分是可以hoist的,比如:style="{ color: 'red' }"就没有动态的值,这个时候可以staticHoist;3. 有部分属性是动态的,flag类型是PROPS,这个时候之前收集的动态prop就很有用了,到时候patch时不需要diff所有属性,只需要diff这些个动态的即可;4. 最后一种和事件有关,标记为HYDRATE_EVENTS,也就是混合事件。
如果不需要开启block && 没有flag或者flag是HYDRATE_EVENTS && 有ref属性或者有生命周期监听的hook(比如@vue:updated)或者存在动态的指令需要在runtime确定的,这个时候标记为NEED_PATCH,来看下这个类型的注释:Indicates an element that only needs non-props patching, e.g. ref or directives (onVnodeXXX hooks). since every patched vnode checks for refs and onVnodeXXX hooks, it simply marks the vnode so that a parent block will track it.,也就是到时候patch只关注non-props比如事件什么的就行了,而不是跟踪所有的属性。
现在我们分门别类好了,但是还有些地方需要深入处理,比如:style="{ xx: xx }",这个动态style的表达式也就是exp里面的字段就有可能是一个动态的,如果有,那就说明得到runtime去处理了。CLASS需要创建一个函数调用表达式节点,辅助函数是NORMALIZE_CLASS。同理STYLE的需要NORMALIZE_STYLE。如果你这个元素/组件节点有动态key,不好意思,上面的判断style/class的就不需要了,反正跑不掉,直接NORMALIZE_PROPS乱棍打死。


最后返回
{
props: propsExpression,
directives: runtimeDirectives,
patchFlag,
dynamicPropNames,
shouldUseBlock
}props:propsExpression,属性表达式节点,正常情况下的事件/属性都放到这里面directives:runtimeDirectives,自定义指令数组patchFlag:不多说dynamicPropNames:动态key数组shouldUseBlock:指的是你这个节点是否需要开启block,比如有用到@vue:before-update的监听子组件生命周期的情况。
**buildProps**这货代码咱也不看了,这里说下发生了什么。由于这货比较特殊,所以它不是一个directiveTreansform插件,在buildProps处理完之后才会处理。
v-slot这玩意儿只会用在component里面。
上来直接把withCtx这个辅助函数存到context里。
如果这个v-slot是在另一个v-slot或者v-for的scope里面的话,并且只有在这个v-slot中使用了scope variable的情况下才会被定义为dynamic,除此之外则是static的(前提是prefixIdentifiers: true)。
v-slot仅能用于template或者component这两种标签上面:
- 如果是放到
component上面,会创建一个对象属性节点,key是arg,没有就创建一个新的单一表达式,key的content是default,而value则是一个函数。如果这里的arg也就是v-slot:xx="aa"里的xx是一个动态的,比如v-slot[xx]="aa",那么这个v-slot就会被标记为dynamic。 - 如果是
template上面的,那就需要判断几种场景:
- 搭配
v-if的场景,如果搭配了v-if,那就肯定是dynamic了,因为runtime阶段可能切换slot。会创建一个条件表表达式节点。如果是v-elsei(-if),操作类似transformIf里的,找到IF的节点,让后将当前节点放到IF节点的branch里,建立if的联系。它也是创建一个条件表达式节点。 - 如果搭配
v-for的场景,它也是动态的。直接就是将for的renderList放到createSlot里面。
为什么会有上面两种兼容场景呢?因为我们在transformIf和transformFor的时候绕过了v-slot的场景,所以这里自然就得处理这两种场景。
接着兼容处理,如果你这个component里存在子节点,但是没有一处地方有v-slot的指令,那也是可以的,实际上这也是大多数时候我们写的slot代码,默认是创建一个defaultSlotProperty节点。
然后就是插旗啦:
-
- 如果是动态的,则是
SlotFlags.DYNAMIC,注释:The parent will need to force the child to update because the slot does not fully capture its dependencies.为了安全考虑,还是把它也一起更新了。 - 如果是盖中盖也就是类型为
SlotFlags.FORWARD,比如<template></template>,把一个插槽传给了组件,这样就能盖中盖了。 - 除此之外都是
stable的了
- 如果是动态的,则是

trackSlotScopes#
const defaultFallback = createSimpleExpression(`undefined`, false)
// A NodeTransform that:
// 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
// by transformExpression. This is only applied in non-browser builds with
// { prefixIdentifiers: true }.
// 2. Track v-slot depths so that we know a slot is inside another slot.
// Note the exit callback is executed before buildSlots() on the same node,
// so only nested slots see positive numbers.
export const trackSlotScopes: NodeTransform = (node, context) => {
if (
node.type === NodeTypes.ELEMENT &&
(node.tagType === ElementTypes.COMPONENT ||
node.tagType === ElementTypes.TEMPLATE)
) {
// We are only checking non-empty v-slot here
// since we only care about slots that introduce scope variables.
const vSlot = findDir(node, 'slot')
if (vSlot) {
const slotProps = vSlot.exp
if (!__BROWSER__ && context.prefixIdentifiers) {
slotProps && context.addIdentifiers(slotProps)
}
context.scopes.vSlot++
return () => {
if (!__BROWSER__ && context.prefixIdentifiers) {
slotProps && context.removeIdentifiers(slotProps)
}
context.scopes.vSlot--
}
}
}
}这个插件看名字就知道是用来跟踪slot的变量相关的。
代码也没啥好说的了,和trackVForSlotScopes这个做的活儿一样,进入到当前节点就将scopes.vSlot++并且将slot的数据放到context.identifiers上。然后返回回调,当回调被执行的时候就意味着所有子节点都已经处理完了,自然就可以退出当前vslot的scope了。
transformText#
// Merge adjacent text nodes and expressions into a single expression
// e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
export const transformText: NodeTransform = (node, context) => {
if (
node.type === NodeTypes.ROOT ||
node.type === NodeTypes.ELEMENT ||
node.type === NodeTypes.FOR ||
node.type === NodeTypes.IF_BRANCH
) {
// perform the transform on node exit so that all expressions have already
// been processed.
return () => {
const children = node.children
let currentContainer: CompoundExpressionNode | undefined = undefined
let hasText = false
for (let i = 0; i < children.length; i++) {
const child = children[i]
if (isText(child)) {
hasText = true
for (let j = i + 1; j < children.length; j++) {
const next = children[j]
if (isText(next)) {
if (!currentContainer) {
currentContainer = children[i] = createCompoundExpression(
[child],
child.loc
)
}
// merge adjacent text node into current
currentContainer.children.push(` + `, next)
children.splice(j, 1)
j--
} else {
currentContainer = undefined
break
}
}
}
}
if (
!hasText ||
// if this is a plain element with a single text child, leave it
// as-is since the runtime has dedicated fast path for this by directly
// setting textContent of the element.
// for component root it's always normalized anyway.
(children.length === 1 &&
(node.type === NodeTypes.ROOT ||
(node.type === NodeTypes.ELEMENT &&
node.tagType === ElementTypes.ELEMENT &&
// #3756
// custom directives can potentially add DOM elements arbitrarily,
// we need to avoid setting textContent of the element at runtime
// to avoid accidentally overwriting the DOM elements added
// by the user through custom directives.
!node.props.find(
p =>
p.type === NodeTypes.DIRECTIVE &&
!context.directiveTransforms[p.name]
) &&
// in compat mode, <template> tags with no special directives
// will be rendered as a fragment so its children must be
// converted into vnodes.
!(__COMPAT__ && node.tag === 'template'))))
) {
return
}
// pre-convert text nodes into createTextVNode(text) calls to avoid
// runtime normalization.
for (let i = 0; i < children.length; i++) {
const child = children[i]
if (isText(child) || child.type === NodeTypes.COMPOUND_EXPRESSION) {
const callArgs: CallExpression['arguments'] = []
// createTextVNode defaults to single whitespace, so if it is a
// single space the code could be an empty call to save bytes.
if (child.type !== NodeTypes.TEXT || child.content !== ' ') {
callArgs.push(child)
}
// mark dynamic text with flag so it gets patched inside a block
if (
!context.ssr &&
getConstantType(child, context) === ConstantTypes.NOT_CONSTANT
) {
callArgs.push(
PatchFlags.TEXT +
(__DEV__ ? ` /* ${PatchFlagNames[PatchFlags.TEXT]} */` : ``)
)
}
children[i] = {
type: NodeTypes.TEXT_CALL,
content: child,
loc: child.loc,
codegenNode: createCallExpression(
context.helper(CREATE_TEXT),
callArgs
)
}
}
}
}
}
}这个其实也是没啥好说的..
- 将前后两个文本节点拼接成一个节点,这里的文本节点指的是
NodeTypes.INTERPOLATION || NodeTypes.TEXT。 - 满足以下条件的节点可以视作为文本节点(逻辑与):
- 这个节点是元素节点或者是根节点
- 这个节点没有任何的指令
- 这个节点只有一个子节点
- 这个子节点是一个文本节点
- 提前创建
VNode,我们前面说了codegenNode是在transformElement插件中生成的,但是那里处理的时候只是处理元素节点和组件节点,其它的都不处理。所以这里并不冲突。辅助函数是createText

directiveTransforms#
现在我们分析完了nodeTransforms里面注册的插件(不包括compiler-dom和compiler-sfc传入的,感兴趣的可以去之前的文章里看下)
而directiveTransforms里面的插件好像没看到地方调用?实际上有,在buildProps中调用了,用来处理元素/组件节点的props。但是buildProps方法由于篇幅的问题我们并没有贴出来代码,这里把调用的那部分叠出来
const directiveTransform = context.directiveTransforms[name]
if (directiveTransform) {
// has built-in directive transform.
const { props, needRuntime } = directiveTransform(prop, node, context)
!ssr && props.forEach(analyzePatchFlag)
if (isVOn && arg && !isStaticExp(arg)) {
pushMergeArg(createObjectExpression(props, elementLoc))
} else {
properties.push(...props)
}
if (needRuntime) {
runtimeDirectives.push(prop)
if (isSymbol(needRuntime)) {
directiveImportMap.set(prop, needRuntime)
}
}
}现在就让我们进入到具体的指令处理插件中分析下代码(有的就不分析了,比如v-on的,之前在compiler-dom里面分析完了)
transformOn#
这个插件之前在compiler-dom里面分析过了。
vue/compiler-dom源码分析学习--day3: 转换指令 - 知乎 (zhihu.com)
这里就不说了,来看下render function

transformBind#
// v-bind without arg is handled directly in ./transformElements.ts due to it affecting
// codegen for the entire props object. This transform here is only for v-bind
// *with* args.
export const transformBind: DirectiveTransform = (dir, _node, context) => {
const { exp, modifiers, loc } = dir
const arg = dir.arg!
if (arg.type !== NodeTypes.SIMPLE_EXPRESSION) {
arg.children.unshift(`(`)
arg.children.push(`) || ""`)
} else if (!arg.isStatic) {
arg.content = `${arg.content} || ""`
}
// .sync is replaced by v-model:arg
if (modifiers.includes('camel')) {
if (arg.type === NodeTypes.SIMPLE_EXPRESSION) {
if (arg.isStatic) {
arg.content = camelize(arg.content)
} else {
arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`
}
} else {
arg.children.unshift(`${context.helperString(CAMELIZE)}(`)
arg.children.push(`)`)
}
}
if (!context.inSSR) {
if (modifiers.includes('prop')) {
injectPrefix(arg, '.')
}
if (modifiers.includes('attr')) {
injectPrefix(arg, '^')
}
}
if (
!exp ||
(exp.type === NodeTypes.SIMPLE_EXPRESSION && !exp.content.trim())
) {
context.onError(createCompilerError(ErrorCodes.X_V_BIND_NO_EXPRESSION, loc))
return {
props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
}
}
return {
props: [createObjectProperty(arg, exp)]
}
}exp:老熟人了,等号右边的表达式modifiers:也是老熟人,修饰符arg:也是,等号左边指令右边的内容,比如v-on:click.once="handle",这个click就是arg,而这个handle就是exp,而这个once自然就是修饰符了。
这些都是在parse阶段就处理好的。
先是对arg做空值保护,然后处理camel修饰符。
这个修饰符可以把你的属性名字驼峰化。如果这个arg是一个动态的,比如v-bind:[test]="xxx",那么这个test就是一个动态的。这个时候就只能借助辅助函数camelize来处理了,否则可以直接在编译阶段就camlize。

接下来处理3.2引入的v-bind的两个修饰符.prop和.attr。

.prop可以强制这个绑定的属性变成property.attr同上,变成attribute
那么问题来了,prop和attribute有啥不同呢?
可以看下这篇文章,这里就不说了。
injectPrefix:看名字就知道是用来注入前缀的,实际上确实如此,所以代码就不看了,不过这里还需要处理动态的arg。

最后直接就创建一个对象属性节点并返回。
transformModel#
在分析之前,先来看下/复习下vue3.x中v-model的用法,做了一些breaking update。
Built-in Directives | Vue.js (vuejs.org)
2.x -> 3.x迁移文档:v-model | Vue 3 Migration Guide (vuejs.org)
另外里面涉及到的inline mode的代码我这里也不会分析
export const transformModel: DirectiveTransform = (dir, node, context) => {
const { exp, arg } = dir
if (!exp) {
context.onError(
createCompilerError(ErrorCodes.X_V_MODEL_NO_EXPRESSION, dir.loc)
)
return createTransformProps()
}
const rawExp = exp.loc.source
const expString =
exp.type === NodeTypes.SIMPLE_EXPRESSION ? exp.content : rawExp
// im SFC <script setup> inline mode, the exp may have been transformed into
// _unref(exp)
const bindingType = context.bindingMetadata[rawExp]
const maybeRef =
!__BROWSER__ &&
context.inline &&
bindingType &&
bindingType !== BindingTypes.SETUP_CONST
if (
!expString.trim() ||
(!isMemberExpression(expString, context) && !maybeRef)
) {
context.onError(
createCompilerError(ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION, exp.loc)
)
return createTransformProps()
}
if (
!__BROWSER__ &&
context.prefixIdentifiers &&
isSimpleIdentifier(expString) &&
context.identifiers[expString]
) {
context.onError(
createCompilerError(ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE, exp.loc)
)
return createTransformProps()
}
const propName = arg ? arg : createSimpleExpression('modelValue', true)
const eventName = arg
? isStaticExp(arg)
? `onUpdate:${arg.content}`
: createCompoundExpression(['"onUpdate:" + ', arg])
: `onUpdate:modelValue`
let assignmentExp: ExpressionNode
const eventArg = context.isTS ? `($event: any)` : `$event`
if (maybeRef) {
if (bindingType === BindingTypes.SETUP_REF) {
// v-model used on known ref.
assignmentExp = createCompoundExpression([
`${eventArg} => ((`,
createSimpleExpression(rawExp, false, exp.loc),
`).value = $event)`
])
} else {
// v-model used on a potentially ref binding in <script setup> inline mode.
// the assignment needs to check whether the binding is actually a ref.
const altAssignment =
bindingType === BindingTypes.SETUP_LET ? `${rawExp} = $event` : `null`
assignmentExp = createCompoundExpression([
`${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,
createSimpleExpression(rawExp, false, exp.loc),
`).value = $event : ${altAssignment})`
])
}
} else {
assignmentExp = createCompoundExpression([
`${eventArg} => ((`,
exp,
`) = $event)`
])
}
const props = [
// modelValue: foo
createObjectProperty(propName, dir.exp!),
// "onUpdate:modelValue": $event => (foo = $event)
createObjectProperty(eventName, assignmentExp)
]
// cache v-model handler if applicable (when it doesn't refer any scope vars)
if (
!__BROWSER__ &&
context.prefixIdentifiers &&
!context.inVOnce &&
context.cacheHandlers &&
!hasScopeRef(exp, context.identifiers)
) {
props[1].value = context.cache(props[1].value)
}
// modelModifiers: { foo: true, "bar-baz": true }
if (dir.modifiers.length && node.tagType === ElementTypes.COMPONENT) {
const modifiers = dir.modifiers
.map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
.join(`, `)
const modifiersKey = arg
? isStaticExp(arg)
? `${arg.content}Modifiers`
: createCompoundExpression([arg, ' + "Modifiers"'])
: `modelModifiers`
props.push(
createObjectProperty(
modifiersKey,
createSimpleExpression(
`{ ${modifiers} }`,
false,
dir.loc,
ConstantTypes.CAN_HOIST
)
)
)
}
return createTransformProps(props)
}处理modifier的部分在compiler-dom的包里,这里就不再说了,感兴趣的大佬可以去看下之前的文章。vue/compiler-dom源码分析学习--day3: 转换指令 - 知乎 (zhihu.com)
前面都是在处理错误场景,就不多说了。。
不过这里有一个需要注意的,那就是你这个v-model的exp不能是来自scope的variable,否则会报错:v-model cannot be used on v-for or v-slot scope variables because they are not writable.。scope variable不可写,只能读。而v-model确实需要改写原数据,这样才算是双向绑定。
其实没啥好说的了,实际上v-model算是一种语法糖写法,它在编译阶段会变成下面这样

其实没啥好说的了,实际上v-model算是一种语法糖写法,它在编译阶段会变成下面这样
而在组件中则多了一个prop,那就是modifier,vue3.x中允许通过defineProps去自定义modifier的行为。


最后将这个节点返回出去
genNode#
那么现在对于transform阶段 AST节点的处理以及codegenNode的生成我们已经分析完了,现在我们来到generate阶段,分析每种类型对应的生成render function的场景。
function genNode(node: CodegenNode | symbol | string, context: CodegenContext) {
if (isString(node)) {
context.push(node)
return
}
if (isSymbol(node)) {
context.push(context.helper(node))
return
}
switch (node.type) {
case NodeTypes.ELEMENT:
case NodeTypes.IF:
case NodeTypes.FOR:
__DEV__ &&
assert(
node.codegenNode != null,
`Codegen node is missing for element/if/for node. ` +
`Apply appropriate transforms first.`
)
genNode(node.codegenNode!, context)
break
case NodeTypes.TEXT:
genText(node, context)
break
case NodeTypes.SIMPLE_EXPRESSION:
genExpression(node, context)
break
case NodeTypes.INTERPOLATION:
genInterpolation(node, context)
break
case NodeTypes.TEXT_CALL:
genNode(node.codegenNode, context)
break
case NodeTypes.COMPOUND_EXPRESSION:
genCompoundExpression(node, context)
break
case NodeTypes.COMMENT:
genComment(node, context)
break
case NodeTypes.VNODE_CALL:
genVNodeCall(node, context)
break
case NodeTypes.JS_CALL_EXPRESSION:
genCallExpression(node, context)
break
case NodeTypes.JS_OBJECT_EXPRESSION:
genObjectExpression(node, context)
break
case NodeTypes.JS_ARRAY_EXPRESSION:
genArrayExpression(node, context)
break
case NodeTypes.JS_FUNCTION_EXPRESSION:
genFunctionExpression(node, context)
break
case NodeTypes.JS_CONDITIONAL_EXPRESSION:
genConditionalExpression(node, context)
break
case NodeTypes.JS_CACHE_EXPRESSION:
genCacheExpression(node, context)
break
case NodeTypes.JS_BLOCK_STATEMENT:
genNodeList(node.body, context, true, false)
break
// SSR only types
case NodeTypes.JS_TEMPLATE_LITERAL:
!__BROWSER__ && genTemplateLiteral(node, context)
break
case NodeTypes.JS_IF_STATEMENT:
!__BROWSER__ && genIfStatement(node, context)
break
case NodeTypes.JS_ASSIGNMENT_EXPRESSION:
!__BROWSER__ && genAssignmentExpression(node, context)
break
case NodeTypes.JS_SEQUENCE_EXPRESSION:
!__BROWSER__ && genSequenceExpression(node, context)
break
case NodeTypes.JS_RETURN_STATEMENT:
!__BROWSER__ && genReturnStatement(node, context)
break
/* istanbul ignore next */
case NodeTypes.IF_BRANCH:
// noop
break
default:
if (__DEV__) {
assert(false, `unhandled codegen node type: ${(node as any).type}`)
// make sure we exhaust all possible types
const exhaustiveCheck: never = node
return exhaustiveCheck
}
}
}为了看着方便,我这里把代码再贴一遍。
isString#
如果节点自身就是一个字符串形式的,那直接就能渲染了,都不用runtime的辅助函数。
isSymbol#
如果这节点自身就只有一个辅助函数,那直接就放到helpers集合里
ELEMENT/IF/FOR#
这三种情况是需要递归的,因为可能存在子节点
TEXT#
function genText(
node: TextNode | SimpleExpressionNode,
context: CodegenContext
) {
context.push(JSON.stringify(node.content), node)
}文本节点,将节点内容字符串化
SIMPLE_EXPRESSION#
function genExpression(node: SimpleExpressionNode, context: CodegenContext) {
const { content, isStatic } = node
context.push(isStatic ? JSON.stringify(content) : content, node)
}单节点表达式,如果是静态的内容,直接stringify处理,如果不是就直接push,拼接到runtime的code里。
INTERPOLATION#
function genInterpolation(node: InterpolationNode, context: CodegenContext) {
const { push, helper, pure } = context
if (pure) push(PURE_ANNOTATION)
push(`${helper(TO_DISPLAY_STRING)}(`)
genNode(node.content, context)
push(`)`)
}pure:这个和webpack的tree-shake相关的。PURE_ANNOTATION:/*#__PURE__*/, 声明这个方法可以是pure纯净的,可以被webpack的编译器shake掉。TO_DISPLAY_STRING:toDisplayString辅助函数。
由于{{ xxx }}的xxx可能是一个复合表达式,所以还需要递归处理这个节点的content。

这个a()和b()就是俩callExpression
TEXT_CALL#
这个我们刚分析完的transformText里如果有两个相连的text节点,就会组成一个新的节点,这就是TEXT_CALL节点。这个新节点的codegenNode是一个callExpression,所以也需要递归处理。

COMPOUND_EXPRESSION#
function genCompoundExpression(
node: CompoundExpressionNode,
context: CodegenContext
) {
for (let i = 0; i < node.children!.length; i++) {
const child = node.children![i]
if (isString(child)) {
context.push(child)
} else {
genNode(child, context)
}
}
}这个就是我们经常念叨的复合类型,比如一个表达式里面有两个语句。

COMMENT#
function genComment(node: CommentNode, context: CodegenContext) {
const { push, helper, pure } = context
if (pure) {
push(PURE_ANNOTATION)
}
push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node)
}这个就不多说了,注释节点

VNODE_CALL#
function genVNodeCall(node: VNodeCall, context: CodegenContext) {
const { push, helper, pure } = context
const {
tag,
props,
children,
patchFlag,
dynamicProps,
directives,
isBlock,
disableTracking,
isComponent
} = node
if (directives) {
push(helper(WITH_DIRECTIVES) + `(`)
}
if (isBlock) {
push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `)
}
if (pure) {
push(PURE_ANNOTATION)
}
const callHelper: symbol = isBlock
? getVNodeBlockHelper(context.inSSR, isComponent)
: getVNodeHelper(context.inSSR, isComponent)
push(helper(callHelper) + `(`, node)
genNodeList(
genNullableArgs([tag, props, children, patchFlag, dynamicProps]),
context
)
push(`)`)
if (isBlock) {
push(`)`)
}
if (directives) {
push(`, `)
genNode(directives, context)
push(`)`)
}
}
function genNodeList(
nodes: (string | symbol | CodegenNode | TemplateChildNode[])[],
context: CodegenContext,
multilines: boolean = false,
comma: boolean = true
) {
const { push, newline } = context
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i]
if (isString(node)) {
push(node)
} else if (isArray(node)) {
genNodeListAsArray(node, context)
} else {
genNode(node, context)
}
if (i < nodes.length - 1) {
if (multilines) {
comma && push(',')
newline()
} else {
comma && push(', ')
}
}
}
}
function genNodeListAsArray(
nodes: (string | CodegenNode | TemplateChildNode[])[],
context: CodegenContext
) {
const multilines =
nodes.length > 3 ||
((!__BROWSER__ || __DEV__) && nodes.some(n => isArray(n) || !isText(n)))
context.push(`[`)
multilines && context.indent()
genNodeList(nodes, context, multilines)
multilines && context.deindent()
context.push(`]`)
}这个节点就是最常见的codegenNode节点类型,我们刚分析完的transformElement给元素/组件节点生成的codegenNode就是这个类型。
这里的这个directives不是内置的,而是custom的指令,需要withDirectives辅助函数。
这个genNullableArgs就不看代码了,就是过滤掉你这节点的null数据。
getNodeList:这个方法没啥好说的,就是将子元素递归genNode处理

JS_CALL_EXPRESSION#
function genCallExpression(node: CallExpression, context: CodegenContext) {
const { push, helper, pure } = context
const callee = isString(node.callee) ? node.callee : helper(node.callee)
if (pure) {
push(PURE_ANNOTATION)
}
push(callee + `(`, node)
genNodeList(node.arguments, context)
push(`)`)
}这个也没啥好说的,一个函数调用表达式,辅助函数就是callee。
比如v-on="object"会变成toHandlers(obj)的形式

JS_OBJECT_EXPRESSION#
function genObjectExpression(node: ObjectExpression, context: CodegenContext) {
const { push, indent, deindent, newline } = context
const { properties } = node
if (!properties.length) {
push(`{}`, node)
return
}
const multilines =
properties.length > 1 ||
((!__BROWSER__ || __DEV__) &&
properties.some(p => p.value.type !== NodeTypes.SIMPLE_EXPRESSION))
push(multilines ? `{` : `{ `)
multilines && indent()
for (let i = 0; i < properties.length; i++) {
const { key, value } = properties[i]
// key
genExpressionAsPropertyKey(key, context)
push(`: `)
// value
genNode(value, context)
if (i < properties.length - 1) {
// will only reach this if it's multilines
push(`,`)
newline()
}
}
multilines && deindent()
push(multilines ? `}` : ` }`)
}对象表达式节点,比如一个指令的exp的codegenNode就有可能是一个JS_OBJECT_EXPRESSION,:style="{ xx: xxx }"

JS_ARRAY_EXPRESSION#
function genArrayExpression(node: ArrayExpression, context: CodegenContext) {
genNodeListAsArray(node.elements as CodegenNode[], context)
}
function genNodeListAsArray(
nodes: (string | CodegenNode | TemplateChildNode[])[],
context: CodegenContext
) {
const multilines =
nodes.length > 3 ||
((!__BROWSER__ || __DEV__) && nodes.some(n => isArray(n) || !isText(n)))
context.push(`[`)
multilines && context.indent()
genNodeList(nodes, context, multilines)
multilines && context.deindent()
context.push(`]`)
}这个就不多说了,调用gentNodeListAsArray

JS_CONDITIONAL_EXPRESSION#
function genConditionalExpression(
node: ConditionalExpression,
context: CodegenContext
) {
const { test, consequent, alternate, newline: needNewline } = node
const { push, indent, deindent, newline } = context
if (test.type === NodeTypes.SIMPLE_EXPRESSION) {
const needsParens = !isSimpleIdentifier(test.content)
needsParens && push(`(`)
genExpression(test, context)
needsParens && push(`)`)
} else {
push(`(`)
genNode(test, context)
push(`)`)
}
needNewline && indent()
context.indentLevel++
needNewline || push(` `)
push(`? `)
genNode(consequent, context)
context.indentLevel--
needNewline && newline()
needNewline || push(` `)
push(`: `)
const isNested = alternate.type === NodeTypes.JS_CONDITIONAL_EXPRESSION
if (!isNested) {
context.indentLevel++
}
genNode(alternate, context)
if (!isNested) {
context.indentLevel--
}
needNewline && deindent(true /* without newline */)
}条件表达式节点,比如v-if的场景,用的就是这个

JS_CACHE_EXPRESSION#
function genCacheExpression(node: CacheExpression, context: CodegenContext) {
const { push, helper, indent, deindent, newline } = context
push(`_cache[${node.index}] || (`)
if (node.isVNode) {
indent()
push(`${helper(SET_BLOCK_TRACKING)}(-1),`)
newline()
}
push(`_cache[${node.index}] = `)
genNode(node.value, context)
if (node.isVNode) {
push(`,`)
newline()
push(`${helper(SET_BLOCK_TRACKING)}(1),`)
newline()
push(`_cache[${node.index}]`)
deindent()
}
push(`)`)
}缓存表达式,这个有些陌生但实际上我们是遇到过的,不过是在另一个包compiler-dom分析的时候遇到的。

JS_BLOCK_STATEMENT#
这个就不看代码了,调用的是genNodeList,一个block的表达式,比如v-for搭配v-memo的场景。

剩下的ssr only类型的这里就不看了
总结#
那么这个包中的插件也就都分析完了,这里没有把buildProps和buildSlot的代码贴出来,可能读起来有些没头没脑。。
总之,如果觉得这篇文章对你有帮助的话,点个赞也是可以哒~
发布于 2023-01-23 09:41・IP 属地广东
