Skip to content

Commit

Permalink
fix: clone comments in cloneNode
Browse files Browse the repository at this point in the history
  • Loading branch information
gzzhanghao committed Apr 18, 2021
1 parent 2918703 commit f26659f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 16 deletions.
6 changes: 6 additions & 0 deletions packages/babel-template/test/index.js
Expand Up @@ -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");
Expand Down
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 f26659f

Please sign in to comment.