2

How do I traverse comments with babelTraverse?

babelTraverse(nodes, {
  CommentBlock: (path) => {
    console.log(path)
  },
  CommentLine: (path) => { 
    console.log(path)
  }
})

Error: You gave us a visitor for the node type CommentBlock but it's not a valid type

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

2 Answers2

3

The CommentBlock and CommentLine are not part of the program.body in the ast returned by the babel parser. These comment types live outside of the program body. I am assuming that is why we get the Type error when we add CommentLine and CommentBlock.

The comments for a node can be accessed, using traverse, as follows:

traverse(ast, {
  ClassDeclaration(path) {
    console.log(path.node.leadingComments);
    console.log(path.node.trailingComments);
  },
});
NSaran
  • 561
  • 3
  • 19
2

Seems like you can't traverse that way but you can access comments with:

nodes.comments

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424