Skip to content

Commit e58a65a

Browse files
committed
omit unnecessary nullish coallescing in template expressions
1 parent 700029b commit e58a65a

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

.changeset/cuddly-walls-pretend.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: omit unnecessary nullish coallescing in template expressions

packages/svelte/src/compiler/phases/3-transform/client/visitors/shared/utils.js

+16-1
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,22 @@ export function build_template_chunk(
119119
// extra work in the template_effect (instead we do the work in set_text).
120120
return { value, has_state };
121121
} else {
122-
expressions.push(b.logical('??', value, b.literal('')));
122+
let expression = value;
123+
// only add nullish coallescence if it hasn't been added already
124+
if (value.type === 'LogicalExpression' && value.operator === '??') {
125+
const { right } = value;
126+
// `undefined` isn't a Literal (due to pre-ES5 shenanigans), so the only nullish literal is `null`
127+
// however, you _can_ make a variable called `undefined` in a Svelte component, so we can't just treat it the same way
128+
if (right.type !== 'Literal') {
129+
expression = b.logical('??', value, b.literal(''));
130+
} else if (right.value === null) {
131+
// if they do something weird like `stuff ?? null`, replace `null` with empty string
132+
value.right = b.literal('');
133+
}
134+
} else {
135+
expression = b.logical('??', value, b.literal(''));
136+
}
137+
expressions.push(expression);
123138
}
124139

125140
quasi = b.quasi('', i + 1 === values.length);

0 commit comments

Comments
 (0)