Skip to content

Commit 7740d45

Browse files
authored
fix: optimise || expressions in template (#15092)
1 parent c2e805f commit 7740d45

File tree

2 files changed

+18
-13
lines changed

2 files changed

+18
-13
lines changed

.changeset/large-islands-cover.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: optimise || expressions in template

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

+13-13
Original file line numberDiff line numberDiff line change
@@ -118,22 +118,22 @@ export function build_template_chunk(
118118
// extra work in the template_effect (instead we do the work in set_text).
119119
return { value, has_state };
120120
} else {
121-
let expression = value;
122-
// only add nullish coallescence if it hasn't been added already
123-
if (value.type === 'LogicalExpression' && value.operator === '??') {
124-
const { right } = value;
125-
// `undefined` isn't a Literal (due to pre-ES5 shenanigans), so the only nullish literal is `null`
126-
// however, you _can_ make a variable called `undefined` in a Svelte component, so we can't just treat it the same way
127-
if (right.type !== 'Literal') {
128-
expression = b.logical('??', value, b.literal(''));
129-
} else if (right.value === null) {
130-
// if they do something weird like `stuff ?? null`, replace `null` with empty string
131-
value.right = b.literal('');
121+
// add `?? ''` where necessary (TODO optimise more cases)
122+
if (
123+
value.type === 'LogicalExpression' &&
124+
value.right.type === 'Literal' &&
125+
(value.operator === '??' || value.operator === '||')
126+
) {
127+
// `foo ?? null` -=> `foo ?? ''`
128+
// otherwise leave the expression untouched
129+
if (value.right.value === null) {
130+
value = { ...value, right: b.literal('') };
132131
}
133132
} else {
134-
expression = b.logical('??', value, b.literal(''));
133+
value = b.logical('??', value, b.literal(''));
135134
}
136-
expressions.push(expression);
135+
136+
expressions.push(value);
137137
}
138138

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

0 commit comments

Comments
 (0)