Skip to content

Commit

Permalink
fix: clone comments in cloneNode (#13178)
Browse files Browse the repository at this point in the history
  • Loading branch information
gzzhanghao committed Apr 20, 2021
1 parent 86d9cf5 commit ab06cca
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
25 changes: 9 additions & 16 deletions packages/babel-types/src/clone/cloneNode.ts
Expand Up @@ -102,25 +102,18 @@ export default function cloneNode<T extends t.Node>(
return newNode;
}

function cloneCommentsWithoutLoc<T extends t.Comment>(
comments: ReadonlyArray<T>,
): T[] {
return comments.map(
({ type, value }) =>
({
type,
value,
loc: null,
} as T),
);
}

function maybeCloneComments<T extends t.Comment>(
comments: ReadonlyArray<T> | null,
deep: boolean,
withoutLoc: boolean,
): ReadonlyArray<T> | 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;
});
}
3 changes: 3 additions & 0 deletions packages/babel-types/test/cloning.js
Expand Up @@ -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,
);
Expand Down

0 comments on commit ab06cca

Please sign in to comment.