diff --git a/lib/printer.ts b/lib/printer.ts index e3f834f0..e0b32d28 100644 --- a/lib/printer.ts +++ b/lib/printer.ts @@ -661,13 +661,19 @@ function genericPrintNoParens(path: any, options: any, print: any) { parts.push("return"); if (n.argument) { - const argLines = path.call(print, "argument"); + const argIsJsxElement = namedTypes.JSXElement?.check(n.argument) + + let argLines = path.call(print, "argument"); if ( argLines.startsWithComment() || - (argLines.length > 1 && - namedTypes.JSXElement && - namedTypes.JSXElement.check(n.argument)) + (argLines.length > 1 && argIsJsxElement) ) { + // Babel: regenerate parenthesized jsxElements so we don't double parentheses + if (argIsJsxElement && n.argument.extra?.parenthesized) { + n.argument.extra.parenthesized = false; + argLines = path.call(print, "argument"); + n.argument.extra.parenthesized = true; + } parts.push(" (\n", argLines.indent(options.tabWidth), "\n)"); } else { parts.push(" ", argLines); diff --git a/test/jsx.ts b/test/jsx.ts index 37f9d9ae..87895f87 100644 --- a/test/jsx.ts +++ b/test/jsx.ts @@ -93,3 +93,35 @@ it("should not remove trailing whitespaces", function () { "}", ); }); + +it("should not double parentheses in Babel", function () { + const printer = new Printer({ tabWidth: 2 }); + const source = + "function App() {\n" + + ' const name = "world";\n' + + "\n" + + " return (\n" + + '
\n' + + " hello {name}\n" + + "
\n" + + " );\n" + + "}"; + + const ast = parse(source, {parser: require("../parsers/babel")}); + ast.program.body[0].body.body[1].argument.openingElement.attributes[0].name.name = + "abc"; + + const code = printer.printGenerically(ast).code; + + assert.equal( + code, + "function App() {\n" + + ' const name = "world";\n' + + "\n" + + " return (\n" + + '
hello {name}\n' + + "
\n" + + " );\n" + + "}", + ); +});