Skip to content

Commit 0fe567a

Browse files
authored
fix(compiler-core): properly transform replaced nodes (#2927)
1 parent 5db2b14 commit 0fe567a

File tree

2 files changed

+45
-10
lines changed

2 files changed

+45
-10
lines changed

packages/compiler-core/__tests__/transforms/transformElement.spec.ts

+33-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import {
33
baseParse as parse,
44
transform,
55
ErrorCodes,
6-
BindingTypes
6+
BindingTypes,
7+
NodeTransform
78
} from '../../src'
89
import {
910
RESOLVE_COMPONENT,
@@ -939,4 +940,35 @@ describe('compiler: element transform', () => {
939940
isBlock: true
940941
})
941942
})
943+
944+
test('should process node when node has been replaced', () => {
945+
// a NodeTransform that swaps out <div id="foo" /> with <span id="foo" />
946+
const customNodeTransform: NodeTransform = (node, context) => {
947+
if (
948+
node.type === NodeTypes.ELEMENT &&
949+
node.tag === 'div' &&
950+
node.props.some(
951+
prop =>
952+
prop.type === NodeTypes.ATTRIBUTE &&
953+
prop.name === 'id' &&
954+
prop.value &&
955+
prop.value.content === 'foo'
956+
)
957+
) {
958+
context.replaceNode({
959+
...node,
960+
tag: 'span'
961+
})
962+
}
963+
}
964+
const ast = parse(`<div><div id="foo" /></div>`)
965+
transform(ast, {
966+
nodeTransforms: [transformElement, transformText, customNodeTransform]
967+
})
968+
expect((ast as any).children[0].children[0].codegenNode).toMatchObject({
969+
type: NodeTypes.VNODE_CALL,
970+
tag: '"span"',
971+
isBlock: false
972+
})
973+
})
942974
})

packages/compiler-core/src/transforms/transformElement.ts

+12-9
Original file line numberDiff line numberDiff line change
@@ -62,18 +62,21 @@ const directiveImportMap = new WeakMap<DirectiveNode, symbol>()
6262

6363
// generate a JavaScript AST for this element's codegen
6464
export const transformElement: NodeTransform = (node, context) => {
65-
if (
66-
!(
67-
node.type === NodeTypes.ELEMENT &&
68-
(node.tagType === ElementTypes.ELEMENT ||
69-
node.tagType === ElementTypes.COMPONENT)
70-
)
71-
) {
72-
return
73-
}
7465
// perform the work on exit, after all child expressions have been
7566
// processed and merged.
7667
return function postTransformElement() {
68+
node = context.currentNode!
69+
70+
if (
71+
!(
72+
node.type === NodeTypes.ELEMENT &&
73+
(node.tagType === ElementTypes.ELEMENT ||
74+
node.tagType === ElementTypes.COMPONENT)
75+
)
76+
) {
77+
return
78+
}
79+
7780
const { tag, props } = node
7881
const isComponent = node.tagType === ElementTypes.COMPONENT
7982

0 commit comments

Comments
 (0)