Skip to content

Commit

Permalink
omit "()" after new when minifying
Browse files Browse the repository at this point in the history
  • Loading branch information
evanw committed Sep 6, 2020
1 parent 5cf587a commit 48991b3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 8 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

* Remove trailing `()` from `new` when minifying

Now `new Foo()` will be printed as `new Foo` when minifying (as long as it's safe to do so), resulting in slightly shorter minified code.

## 0.6.31

* Invalid source maps are no longer an error ([#367](https://github.com/evanw/esbuild/issues/367))
Expand Down
18 changes: 10 additions & 8 deletions internal/printer/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -1292,16 +1292,18 @@ func (p *printer) printExpr(expr ast.Expr, level ast.L, flags int) {
p.printSpace()
p.printExpr(e.Target, ast.LNew, forbidCall)

// TODO: Omit this while minifying
p.print("(")
for i, arg := range e.Args {
if i != 0 {
p.print(",")
p.printSpace()
// Omit the "()" when minifying, but only when safe to do so
if !p.options.RemoveWhitespace || len(e.Args) > 0 || level >= ast.LPostfix {
p.print("(")
for i, arg := range e.Args {
if i != 0 {
p.print(",")
p.printSpace()
}
p.printExpr(arg, ast.LComma, 0)
}
p.printExpr(arg, ast.LComma, 0)
p.print(")")
}
p.print(")")

if wrap {
p.print(")")
Expand Down
7 changes: 7 additions & 0 deletions internal/printer/printer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,13 @@ func TestNew(t *testing.T) {
expectPrinted(t, "new (import('foo')).bar", "new (import(\"foo\")).bar();\n")
expectPrinted(t, "new (import('foo')[bar])", "new (import(\"foo\"))[bar]();\n")
expectPrinted(t, "new (import('foo'))[bar]", "new (import(\"foo\"))[bar]();\n")

expectPrintedMinify(t, "new x", "new x;")
expectPrintedMinify(t, "new x.y", "new x.y;")
expectPrintedMinify(t, "(new x).y", "new x().y;")
expectPrintedMinify(t, "new x().y", "new x().y;")
expectPrintedMinify(t, "new x() + y", "new x+y;")
expectPrintedMinify(t, "new x() ** 2", "new x**2;")
}

func TestCall(t *testing.T) {
Expand Down

0 comments on commit 48991b3

Please sign in to comment.