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

feat(compiler-sfc): ignore empty blocks #3520

Merged
merged 1 commit into from
Jul 19, 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
5 changes: 5 additions & 0 deletions packages/compiler-sfc/__tests__/parse.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,13 @@ h1 { color: red }

test('should ignore other nodes with no content', () => {
expect(parse(`<script/>`).descriptor.script).toBe(null)
expect(parse(`<script> \n\t </script>`).descriptor.script).toBe(null)
expect(parse(`<style/>`).descriptor.styles.length).toBe(0)
expect(parse(`<style> \n\t </style>`).descriptor.styles.length).toBe(0)
expect(parse(`<custom/>`).descriptor.customBlocks.length).toBe(0)
expect(
parse(`<custom> \n\t </custom>`).descriptor.customBlocks.length
).toBe(0)
})

test('handle empty nodes with src attribute', () => {
Expand Down
15 changes: 14 additions & 1 deletion packages/compiler-sfc/src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ export function parse(
if (node.type !== NodeTypes.ELEMENT) {
return
}
if (!node.children.length && !hasSrc(node) && node.tag !== 'template') {
// we only want to keep the nodes that are not empty (when the tag is not a template)
if (node.tag !== 'template' && isEmpty(node) && !hasSrc(node)) {
return
}
switch (node.tag) {
Expand Down Expand Up @@ -374,3 +375,15 @@ function hasSrc(node: ElementNode) {
return p.name === 'src'
})
}

/**
* Returns true if the node has no children
* once the empty text nodes (trimmed content) have been filtered out.
*/
function isEmpty(node: ElementNode) {
return (
node.children.filter(
child => child.type !== NodeTypes.TEXT || child.content.trim() !== ''
).length === 0
)
}