Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(transformElement): properly transform replaced nodes #2927

Merged
merged 2 commits into from
Mar 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import {
baseParse as parse,
transform,
ErrorCodes,
BindingTypes
BindingTypes,
NodeTransform
} from '../../src'
import {
RESOLVE_COMPONENT,
Expand Down Expand Up @@ -939,4 +940,35 @@ describe('compiler: element transform', () => {
isBlock: true
})
})

test('should process node when node has been replaced', () => {
// a NodeTransform that swaps out <div id="foo" /> with <span id="foo" />
const customNodeTransform: NodeTransform = (node, context) => {
if (
node.type === NodeTypes.ELEMENT &&
node.tag === 'div' &&
node.props.some(
prop =>
prop.type === NodeTypes.ATTRIBUTE &&
prop.name === 'id' &&
prop.value &&
prop.value.content === 'foo'
)
) {
context.replaceNode({
...node,
tag: 'span'
})
}
}
const ast = parse(`<div><div id="foo" /></div>`)
transform(ast, {
nodeTransforms: [transformElement, transformText, customNodeTransform]
})
expect((ast as any).children[0].children[0].codegenNode).toMatchObject({
type: NodeTypes.VNODE_CALL,
tag: '"span"',
isBlock: false
})
})
})
21 changes: 12 additions & 9 deletions packages/compiler-core/src/transforms/transformElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,21 @@ const directiveImportMap = new WeakMap<DirectiveNode, symbol>()

// generate a JavaScript AST for this element's codegen
export const transformElement: NodeTransform = (node, context) => {
if (
!(
node.type === NodeTypes.ELEMENT &&
(node.tagType === ElementTypes.ELEMENT ||
node.tagType === ElementTypes.COMPONENT)
)
) {
return
}
// 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

Expand Down