Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Javascript Comments

While the point of Javascript comments (in fact, comments in general) is that they are not parsed by the compiler, I was wondering if there is a way to actually read comments using Javascript - i.e.

/* Hello, world! */
function readComment() {
    alert(readsTheCommentSomehow()) //Would alert "Hello, World!"
}

The use case of something like this would be something like Javadoc, or something cooler like getting code to change what it does dependant of the comment above it. I'm sure that there are other reasons to want to do this, too.

So far, the only way that I have considered doing this is by actually (somehow) making the Javascript read its own code, split by things like /*, \n, //, */ and return the comments that way.

Is this really the best way to approach this problem, or am I missing something?

like image 223
Toastrackenigma Avatar asked Jun 08 '26 18:06

Toastrackenigma


1 Answers

You can use an AST parser and transformer like babel to read and change your code. Following is simple and naive example on how to read and change tour code according to your comments: http://astexplorer.net/#/5ezZ2lwYHQ

original code:

// does something
// and other stuff
function doSomething() {
  console.log('hello');
}

babel ast transformer:

export default function ({types: t}) {
  return {
    visitor: {
      FunctionDeclaration(path) {
        if (path.node.leadingComments) {
          const text = path.node.leadingComments.map(comment => comment.value).join('\n');
          const change = t.expressionStatement(
            t.callExpression(
              t.memberExpression(t.identifier('console'), t.identifier('log')), 
                [
                  t.stringLiteral(`Function has comments:${text}`)
                ]));

          path.node.body.body.unshift(change);
        }
      }
    }
  };
}
like image 137
yairhaimo Avatar answered Jun 11 '26 08:06

yairhaimo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!