facebook / jscodeshift

A JavaScript codemod toolkit.
https://jscodeshift.com
MIT License
9.11k stars 468 forks source link

It seems we can't add a comment at the bottom of the target node? #547

Open Indomi opened 1 year ago

Indomi commented 1 year ago

with babylon parser

I can use j.commentLine() api to add a comment for node, but the result is, I can only control the comment with related code in the same line or before the code, if I need to add comments at the bottom of the node, it seems I can only find the siblings node which is after the target, and add comment to it?

hope to receive reply, thanks!

ElonVolo commented 1 year ago

The Recast library, which is responsible for printing the transformed output from jscodeshift, is limited in what it can do with comments. I'm guessing that this is what you're running into.

Daniel15 commented 1 year ago

Comments are tricky since "trivia" (whitespace and comments) are not actually part of a normal AST. Different systems represent it differently - sometimes you need a "full syntax tree" or "lossless syntax tree" to get the trivia, other times it's hacked into the AST as a property of a node (e.g. nodes own the comments directly above them, and all the whitespace after them until the next node).

I think with jscodeshift and the libraries it uses, the comments are there but nodes only own the comments above them, so you'd have to find the next sibling node and add a comment to it.