Skip to content

Commit

Permalink
feat(transformer/class-properties): do not create temp var for templa…
Browse files Browse the repository at this point in the history
…te literal computed key (#7919)

Do not create temp var for computed key which is `TemplateLiteral` with no expressions. Evaluating such a template literal cannot have side effects.

```js
class C {
  [`foo`] = 1;
}
```

But this *can* have side effects:

```js
class C {
  [`foo${bar}`] = 1;
}
```
  • Loading branch information
overlookmotel committed Dec 15, 2024
1 parent b31f123 commit 02b653c
Showing 1 changed file with 6 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,12 @@ fn key_needs_temp_var(key: &Expression, ctx: &TraverseCtx) -> bool {
| Expression::BigIntLiteral(_)
| Expression::RegExpLiteral(_)
| Expression::StringLiteral(_) => false,
// Template literal cannot have side effects if it has no expressions.
// If it *does* have expressions, but they're all literals, then also cannot have side effects,
// but don't bother checking for that as it shouldn't occur in real world code.
// Why would you write "`x${9}z`" when you can just write "`x9z`"?
// Note: "`x${foo}`" *can* have side effects if `foo` is an object with a `valueOf` method.
Expression::TemplateLiteral(lit) => !lit.expressions.is_empty(),
// `IdentifierReference`s can have side effects if is unbound.
//
// If var is mutated, it also needs a temp var, because of cases like
Expand Down

0 comments on commit 02b653c

Please sign in to comment.