Skip to content

fix: keep comments in opening tags without attributes or containing > - #551

Open
MFA-G wants to merge 1 commit into
sveltejs:mainfrom
MFA-G:fix/tag-comments-without-attributes
Open

MFA-G wants to merge 1 commit into
sveltejs:mainfrom
MFA-G:fix/tag-comments-without-attributes

Conversation

@MFA-G

@MFA-G MFA-G commented Oct 21, 2026

Copy link
Copy Markdown

Fixes sveltejs/language-tools#3151

Comments inside an opening tag were silently deleted in two cases:

<p /* a > b , c */ ></p>      <!-- before: <p></p> -->
<br /* a > b , c */ />        <!-- before: <br /> -->
<div /* comment */></div>     <!-- before: <div></div> -->
<div class="x" /* a > b */></div>  <!-- kept, but only by luck -->

Causes

  1. No attributes: attachAttributeComments only looks at elements whose attributes array is non-empty, so a comment in <p /* c */> was never attached to anything and never printed.
  2. > inside a comment: the end of the opening tag was found with original_text.indexOf('>', last_attr.end), which stops at the > inside the comment. A comment containing > after the last attribute fell outside that range and was dropped.

Fix

  • findOpeningTagEnd scans for the closing > while skipping over the known comment ranges, so a > inside a comment is never taken as the end of the tag.
  • For an element without attributes, the comments between the tag name (or the this={...} expression of <svelte:element>/<svelte:component>) and > are attached as dangling comments on the element. The element printer prints them where attributes would go (printDanglingTagComments). Line comments force the tag to break, and with bracketSameLine the > moves to its own line so it isn't commented out.

Tests

Added test/printer/samples/attribute-comment-without-attributes.html, which covers block and line comments, > inside comments, self-closing and void elements, components, <svelte:element this>, and comments after an attribute. It fails on master and passes with this change. I also checked the output by hand with --bracket-same-line and re-formatted it to make sure it's idempotent.

  • pnpm test: 310 passed
  • pnpm lint: passes
  • pnpm check: shows the same two errors as on master (estree types, implicit any in print/index.ts). This PR adds no new ones.

Changeset included.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Formatter removes comments in specific contexts

1 participant