Files
test-repo/changelog_unreleased/api/18055.md
T

887 B

Pass ancestors to plugin.printer.canAttachComment() (#18055 by @fisker)

This prevent attaching comments to a specific child of node.

For example in this JavaScript code const object = {property};, the Identifier node (property) appears as both Property.key and Property.value in the AST, obviously it can only print once, if the comment is attached to the non-printable child the comment will get lost.

Plugins can now avoid this by adding a canAttachComment like this:

export const canAttachComment = (node, [parent]) =>
  !(
    parent?.type === "Property" &&
    parent.shorthand &&
    parent.key === node &&
    parent.key !== parent.value
  );

export const print = (path, options, print) => {
  const { node } = path;
  switch (node.type) {
    case "Property":
      if (node.shorthand) {
        return print("value");
      }
    // ...
  }
};