From e8768569a042be09be0b01445fbe399ed043793b Mon Sep 17 00:00:00 2001 From: Evan Wallace Date: Fri, 22 Apr 2022 12:24:46 -0400 Subject: [PATCH] fix #2203: `export default` of `/* @__PURE__ */` --- CHANGELOG.md | 20 ++++++++++++++++++++ internal/js_printer/js_printer.go | 4 ++++ internal/js_printer/js_printer_test.go | 10 ++++++++++ 3 files changed, 34 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f205bd473d2..6ee184b038f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## Unreleased + +* Fix code generation for `export default` and `/* @__PURE__ */` call ([#2203](https://github.com/evanw/esbuild/issues/2203)) + + The `/* @__PURE__ */` comment annotation can be added to function calls to indicate that they are side-effect free. These annotations are passed through into the output by esbuild since many JavaScript tools understand them. However, there was an edge case where printing this comment before a function call caused esbuild to fail to parenthesize a function literal because it thought it was no longer at the start of the expression. This problem has been fixed: + + ```js + // Original code + export default /* @__PURE__ */ (function() { + })() + + // Old output + export default /* @__PURE__ */ function() { + }(); + + // New output + export default /* @__PURE__ */ (function() { + })(); + ``` + ## 0.14.38 * Further fixes to TypeScript 4.7 instantiation expression parsing ([#2201](https://github.com/evanw/esbuild/issues/2201)) diff --git a/internal/js_printer/js_printer.go b/internal/js_printer/js_printer.go index 63f2fb1aefa..53965e8ede2 100644 --- a/internal/js_printer/js_printer.go +++ b/internal/js_printer/js_printer.go @@ -1817,10 +1817,14 @@ func (p *printer) printExpr(expr js_ast.Expr, level js_ast.L, flags printExprFla if hasPureComment { wasStmtStart := p.stmtStart == len(p.js) + wasExportDefaultStart := p.exportDefaultStart == len(p.js) p.print("/* @__PURE__ */ ") if wasStmtStart { p.stmtStart = len(p.js) } + if wasExportDefaultStart { + p.exportDefaultStart = len(p.js) + } } // We don't ever want to accidentally generate a direct eval expression here diff --git a/internal/js_printer/js_printer_test.go b/internal/js_printer/js_printer_test.go index 3d88f4ae24c..628bbc25985 100644 --- a/internal/js_printer/js_printer_test.go +++ b/internal/js_printer/js_printer_test.go @@ -547,6 +547,16 @@ func TestPureComment(t *testing.T) { expectPrinted(t, "/*@__PURE__*/new (function() {})()", "/* @__PURE__ */ new function() {\n}();\n") + + expectPrinted(t, + "export default (function() {})", + "export default (function() {\n});\n") + expectPrinted(t, + "export default (function() {})()", + "export default (function() {\n})();\n") + expectPrinted(t, + "export default /*@__PURE__*/(function() {})()", + "export default /* @__PURE__ */ (function() {\n})();\n") } func TestGenerator(t *testing.T) {