Using babel traverse to to get comments in AST

1.6k views Asked by At

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

2

There are 2 answers

0
NSaran On

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);
  },
});
0
ThomasReggi On

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

nodes.comments