From 5d0ec0a5634cda17804098b1b3190c7a165ad4b8 Mon Sep 17 00:00:00 2001 From: Brian Donovan <1938+eventualbuddha@users.noreply.github.com> Date: Sat, 1 Jun 2024 18:06:03 +0000 Subject: [PATCH] fix: prevent removal of trailing JSX whitespace This just re-applies the fix from #1223 by @coderaiser on top of `master`. --- lib/printer.ts | 2 +- test/jsx.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/printer.ts b/lib/printer.ts index dee5dffa..e3f834f0 100644 --- a/lib/printer.ts +++ b/lib/printer.ts @@ -1314,7 +1314,7 @@ function genericPrintNoParens(path: any, options: any, print: any) { typeof child.value === "string" ) { if (/\S/.test(child.value)) { - return child.value.replace(/^\s+|\s+$/g, ""); + return child.value.replace(/^\s+/g, ""); } else if (/\n/.test(child.value)) { return "\n"; } diff --git a/test/jsx.ts b/test/jsx.ts index d4d2e466..37f9d9ae 100644 --- a/test/jsx.ts +++ b/test/jsx.ts @@ -2,6 +2,7 @@ import { parse } from "../lib/parser"; import { Printer } from "../lib/printer"; +import assert from "assert"; import * as types from "ast-types"; const nodeMajorVersion = parseInt(process.versions.node, 10); @@ -61,3 +62,34 @@ for (const { title, parser } of [ }); }); } + +it("should not remove trailing whitespaces", 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); + 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" + + "}", + ); +});