Pass ancestors to plugin.print.canAttachComment() (#18055)

This commit is contained in:
fisker Cheung authored and GitHub committed 2025-10-12 19:56:44 +08:00
1 parent 356e7d9f52
commit 0f74812b5c
10 files changed
+150 -73

No files matched your search

+14 -3
View File
@@ -410,14 +410,25 @@ function printComment(
#### (optional) `canAttachComment`
```ts
function canAttachComment(node: AST): boolean;
function canAttachComment(node: AST, ancestors: T[]): boolean;
```
:::note
The second parameter `ancestors` first added in v3.7.0.
:::
This function is used for deciding whether a comment can be attached to a particular AST node. By default, _all_ AST properties are traversed searching for nodes that comments can be attached to. This function is used to prevent comments from being attached to a particular node. A typical implementation looks like
```js
function canAttachComment(node) {
return node.type && node.type !== "comment";
function canAttachComment(node, [parent]) {
return !(
node.type === "comment" ||
(parent?.type === "shorthand-property" &&
parent.key === node &&
parent.key !== parent.value)
);
}
```