Skip to content

Fix JSX comment duplication in preserve mode #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

Copilot
Copy link

@Copilot Copilot AI commented Jul 9, 2025

This PR fixes a bug where comments adjacent to JSX expressions were duplicated in the emitted output when using jsx: preserve mode.

Problem

When JSX contains comments immediately before or after expressions, TypeScript was emitting those comments twice:

// Input
const jsx = <div>/*pre*/{x}/*post*/</div>;

// Output (incorrect - comments duplicated)
const jsx = <div> /*pre*//*pre*/{x} /*post*//*post*/</div>;

Root Cause

The issue occurred because comments in JSX content are parsed as both:

  1. JSX text nodes containing the comment text (e.g., JsxText with content "/*pre*/")
  2. Trivia comments attached to adjacent JSX expressions

This caused the same comment content to be emitted twice:

  • Once when emitting the JSX text node via emitJsxText()
  • Again when emitting trivia comments via the comment emission logic in emitTokenWithComment()

Solution

The fix prevents duplicate comment emission by:

  1. Adding context tracking: Introduced isEmittingJsxChildren flag to track when we're emitting JSX element children
  2. Suppressing duplicate trivia: Modified emitTokenWithComment() to skip leading/trailing comment emission for JSX expressions when they would duplicate JSX text content
  3. Preserving correct behavior: The fix only affects JSX expressions within JSX children context, leaving other comment emission unchanged

Testing

Added comprehensive test case covering:

  • Basic case: <div>/*pre*/{x}/*post*/</div>
  • Original issue: <App>/* no */{/* 1 */ 123 /* 2 */}/* no */</App>
  • Edge cases: Leading-only and trailing-only comments

The fix works for both jsx: preserve and jsx: react-jsxdev modes.

Addressing #11.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@Copilot Copilot AI changed the title [WIP] JSX comment duplicated Fix JSX comment duplication in preserve mode Jul 9, 2025
Copilot finished work on behalf of RyanCavanaugh July 9, 2025 19:54
@Copilot Copilot AI requested a review from RyanCavanaugh July 9, 2025 19:54
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.

2 participants