facebook / jscodeshift

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

Is there proper way to remove all comments? #293

Open glebcha opened 5 years ago

glebcha commented 5 years ago

Now I have to iterate comment nodes and modify values, but comment's signature is staying untouched. In:

// leading_comment
const definition = 'string'
/* block_comment */

Modification:

const j = api.jscodeshift
const root = j(file.source)

root.find(j.Comment).forEach(comment => (comment.value.value = ''))

Out:

//
const definition = 'string'
/**/

Expected:

const definition = 'string'
fkling commented 5 years ago

This works:

return j(file.source).find(j.Comment).forEach(path => path.prune()).toSource();

https://astexplorer.net/#/gist/1ac239fc11f0c274540e680420313c34/d4a78b1e7ff1eff4f1828e939e545bbf78fde1aa

I was hoping that j(file.source).find(j.Comment).remove().toSource(); but it looks like remove is only defined for Nodes and a comment is not a Node. Maybe we can make it work though.

glebcha commented 5 years ago

This works:

return j(file.source).find(j.Comment).forEach(path => path.prune()).toSource();

Sorry, but with flow parser it became invalid line like export type type Notice = {}

fkling commented 5 years ago

If this is still an issue for you, could you provide a concrete flow example for which this breaks?

Vadko commented 11 months ago

@fkling

This works:

return j(file.source).find(j.Comment).forEach(path => path.prune()).toSource();

https://astexplorer.net/#/gist/1ac239fc11f0c274540e680420313c34/d4a78b1e7ff1eff4f1828e939e545bbf78fde1aa

I was hoping that j(file.source).find(j.Comment).remove().toSource(); but it looks like remove is only defined for Nodes and a comment is not a Node. Maybe we can make it work though.

Although, it is working fine, but there is TS error: Argument of type  Type<Comment>  is not assignable to parameter of type  Type<ASTNode>, and the interesting moment is when instead of j.Comment I try to use j.CommentBlock/j.CommentLine it doesnt remove comments.