From f26659fbe84a55db81ab47f2604aba04dfffc75f Mon Sep 17 00:00:00 2001 From: Jason Date: Sun, 18 Apr 2021 16:33:22 +0800 Subject: [PATCH] fix: clone comments in cloneNode --- packages/babel-template/test/index.js | 6 +++++ packages/babel-types/src/clone/cloneNode.ts | 25 ++++++++------------- packages/babel-types/test/cloning.js | 3 +++ 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/packages/babel-template/test/index.js b/packages/babel-template/test/index.js index ffd55c6f10a3..d90623100301 100644 --- a/packages/babel-template/test/index.js +++ b/packages/babel-template/test/index.js @@ -40,6 +40,12 @@ describe("@babel/template", function () { expect(generator(output2).code).toBe(comments); }); + it("should clone comments", () => { + const build = template(comments, { preserveComments: true }); + const output = t.program([build(), build()]); + expect(generator(output).code).toBe(`${comments}\n\n${comments}`); + }); + describe("string-based", () => { it("should handle replacing values from an object", () => { const value = t.stringLiteral("some string value"); diff --git a/packages/babel-types/src/clone/cloneNode.ts b/packages/babel-types/src/clone/cloneNode.ts index 826d54c53e2a..0e6506a0c752 100644 --- a/packages/babel-types/src/clone/cloneNode.ts +++ b/packages/babel-types/src/clone/cloneNode.ts @@ -102,25 +102,18 @@ export default function cloneNode( return newNode; } -function cloneCommentsWithoutLoc( - comments: ReadonlyArray, -): T[] { - return comments.map( - ({ type, value }) => - ({ - type, - value, - loc: null, - } as T), - ); -} - function maybeCloneComments( comments: ReadonlyArray | null, deep: boolean, withoutLoc: boolean, ): ReadonlyArray | null { - return deep && withoutLoc && comments - ? cloneCommentsWithoutLoc(comments) - : comments; + if (!comments || !deep) { + return comments; + } + return comments.map(({ type, value, loc }) => { + if (withoutLoc) { + return { type, value, loc: null } as T; + } + return { type, value, loc } as T; + }); } diff --git a/packages/babel-types/test/cloning.js b/packages/babel-types/test/cloning.js index 6cbb1cfe0554..61a72ff06889 100644 --- a/packages/babel-types/test/cloning.js +++ b/packages/babel-types/test/cloning.js @@ -120,6 +120,9 @@ describe("cloneNode", function () { node.declarations[0].id.loc = {}; const cloned = t.cloneNode(node, /* deep */ true, /* withoutLoc */ false); + expect(cloned.declarations[0].id.leadingComments[0]).not.toBe( + node.declarations[0].id.leadingComments[0], + ); expect(cloned.declarations[0].id.leadingComments[0].loc).toBe( node.declarations[0].id.leadingComments[0].loc, );