diff --git a/packages/babel-types/src/clone/cloneNode.ts b/packages/babel-types/src/clone/cloneNode.ts index 1ef270afe2..826d54c53e 100644 --- a/packages/babel-types/src/clone/cloneNode.ts +++ b/packages/babel-types/src/clone/cloneNode.ts @@ -102,7 +102,9 @@ export default function cloneNode( return newNode; } -function cloneCommentsWithoutLoc(comments: T[]): T[] { +function cloneCommentsWithoutLoc( + comments: ReadonlyArray, +): T[] { return comments.map( ({ type, value }) => ({ @@ -113,6 +115,12 @@ function cloneCommentsWithoutLoc(comments: T[]): T[] { ); } -function maybeCloneComments(comments, deep, withoutLoc) { - return deep && withoutLoc ? cloneCommentsWithoutLoc(comments) : comments; +function maybeCloneComments( + comments: ReadonlyArray | null, + deep: boolean, + withoutLoc: boolean, +): ReadonlyArray | null { + return deep && withoutLoc && comments + ? cloneCommentsWithoutLoc(comments) + : comments; } diff --git a/packages/babel-types/test/cloning.js b/packages/babel-types/test/cloning.js index c8c3955157..6cbb1cfe05 100644 --- a/packages/babel-types/test/cloning.js +++ b/packages/babel-types/test/cloning.js @@ -42,6 +42,14 @@ describe("cloneNode", function () { expect(t.isNodesEquivalent(node, cloned)).toBe(true); }); + it("should handle deep cloning without loc of fragments", function () { + const program = "foo();"; + const node = parse(program); + const cloned = t.cloneNode(node, /* deep */ true, /* withoutLoc */ true); + expect(node).not.toBe(cloned); + expect(t.isNodesEquivalent(node, cloned)).toBe(true); + }); + it("should handle missing array element", function () { const node = parse("[,0]"); const cloned = t.cloneNode(node);