Skip to content

Commit

Permalink
fix: optional chaining with bracket notation #757
Browse files Browse the repository at this point in the history
  • Loading branch information
ksw2000 committed Oct 24, 2024
1 parent 85a6fdc commit 56a9bac
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
8 changes: 7 additions & 1 deletion js/js.go
Original file line number Diff line number Diff line change
Expand Up @@ -1217,12 +1217,18 @@ func (m *jsMinifier) minifyExpr(i js.IExpr, prec js.OpPrec) {
} else {
m.minifyExpr(expr.X, js.OpMember)
}

// To address issue #757
isWrittenOptChainBytes := false
if expr.Optional {
m.write(optChainBytes)
isWrittenOptChainBytes = true
}
if lit, ok := expr.Y.(*js.LiteralExpr); ok && lit.TokenType == js.StringToken && 2 < len(lit.Data) {
if isIdent := js.AsIdentifierName(lit.Data[1 : len(lit.Data)-1]); isIdent {
m.write(dotBytes)
if !isWrittenOptChainBytes {
m.write(dotBytes)
}
m.write(lit.Data[1 : len(lit.Data)-1])
break
} else if isNum := js.AsDecimalLiteral(lit.Data[1 : len(lit.Data)-1]); isNum {
Expand Down
5 changes: 3 additions & 2 deletions js/js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package js
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"runtime"
"testing"
Expand Down Expand Up @@ -679,6 +678,8 @@ func TestJS(t *testing.T) {
{`a=obj["3name"]`, `a=obj["3name"]`},
{"a=b`tmpl${a?b:b}tmpl`", "a=b`tmpl${a,b}tmpl`"},
{`a=b?.[c]`, `a=b?.[c]`},
{`a=b?.["c"]`, `a=b?.c`}, // Issue 757
{`a=b?.["c d"]`, `a=b?.["c d"]`}, // Issue 757
{`a=b.#c`, `a=b.#c`},
{`a=b().#c`, `a=b().#c`},
{`a=b?.#c`, `a=b?.#c`},
Expand Down Expand Up @@ -977,7 +978,7 @@ func TestRenamerIndices(t *testing.T) {

func BenchmarkJQuery(b *testing.B) {
m := minify.New()
buf, err := ioutil.ReadFile("../benchmarks/sample_jquery.js")
buf, err := os.ReadFile("../benchmarks/sample_jquery.js")
if err != nil {
panic(err)
}
Expand Down

0 comments on commit 56a9bac

Please sign in to comment.