diff --git a/packages/babel-types/src/clone/cloneNode.ts b/packages/babel-types/src/clone/cloneNode.ts index 826d54c53e..0e6506a0c7 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 6cbb1cfe05..61a72ff068 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, );