From 56a9bacfd6e50ee422fea0bc8027c787df8ff37b Mon Sep 17 00:00:00 2001 From: ksw2000 <13825170+ksw2000@users.noreply.github.com> Date: Thu, 24 Oct 2024 15:30:42 +0800 Subject: [PATCH] fix: optional chaining with bracket notation #757 --- js/js.go | 8 +++++++- js/js_test.go | 5 +++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/js/js.go b/js/js.go index 7802d21fa..b421bbf78 100644 --- a/js/js.go +++ b/js/js.go @@ -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 { diff --git a/js/js_test.go b/js/js_test.go index e79a7ed98..fc63a27ae 100644 --- a/js/js_test.go +++ b/js/js_test.go @@ -3,7 +3,6 @@ package js import ( "bytes" "fmt" - "io/ioutil" "os" "runtime" "testing" @@ -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`}, @@ -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) }