Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js: incorrect behavior when minifying optional chaining with bracket notation (a?.["b"]) #757

Closed
ksw2000 opened this issue Oct 24, 2024 · 1 comment

Comments

@ksw2000
Copy link
Contributor

ksw2000 commented Oct 24, 2024

Description

When using the minifier to process JavaScript code that includes optional chaining with bracket notation, such as a?.["b"], the output is incorrect. This issue appears to be the root cause of #744 , where similar behavior was observed. The specific problem lies in how the minifier transforms a?.["b"] into a?..b, which is invalid JavaScript.

Reproduce

In js/js_test.go

func TestOptionalChainingWithBracket (t *testing.T) {
	m := minify.New()
	o := Minifier{KeepVarNames: true, useAlphabetVarNames: true}
	r := bytes.NewBufferString(`
		let a = {
			"b": "foo"
		};
		console.log(a.b);
		console.log(a?.b);
		console.log(a["b"]);
		console.log(a?.["b"]);    // Unexpected Behavior Here!!
	`)
	w := &bytes.Buffer{}
	o.Minify(m, w, r, nil)
	fmt.Println(w)
}
go test --run TestOptionalChainingWithBracket  -v

output:

let a={b:"foo"};console.log(a.b),console.log(a?.b),console.log(a.b),console.log(a?..b)

The last line of the output console.log(a?..b) is incorrect. The minifier improperly handles the bracket notation in optional chaining, resulting in invalid JavaScript syntax.

Expected Behavior

The minified code should correctly preserve the bracket notation in optional chaining. The expected output should be:

let a={b:"foo"};console.log(a.b),console.log(a?.b),console.log(a.b),console.log(a?.["b"])

image

ksw2000 added a commit to ksw2000/minify that referenced this issue Oct 24, 2024
tdewolff added a commit that referenced this issue Oct 24, 2024
fix: js optional chaining with bracket notation #757
@tdewolff
Copy link
Owner

Fixed in v2.21.1, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants