From ab06ccad496a0b654c64eeeddcb51ffba8271970 Mon Sep 17 00:00:00 2001 From: Jason Date: Tue, 20 Apr 2021 22:34:12 +0800 Subject: [PATCH] fix: clone comments in cloneNode (#13178) --- packages/babel-types/src/clone/cloneNode.ts | 25 ++++++++------------- packages/babel-types/test/cloning.js | 3 +++ 2 files changed, 12 insertions(+), 16 deletions(-) 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, );