diff --git a/CHANGELOG.md b/CHANGELOG.md index 0acc0525d89..f8965a36ea6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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)) diff --git a/internal/printer/printer.go b/internal/printer/printer.go index 21e92799e7f..53c9c27c0be 100644 --- a/internal/printer/printer.go +++ b/internal/printer/printer.go @@ -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(")") diff --git a/internal/printer/printer_test.go b/internal/printer/printer_test.go index 98ea9873420..c1ebb383485 100644 --- a/internal/printer/printer_test.go +++ b/internal/printer/printer_test.go @@ -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) {