Comment Collection

Comments do not affect the syntax of a JavaScript program and therefore they are ignored by Esprima parser. However, if it is important to collect every single-line and multi-line comment in the program, Esprima parser can be instructed to collect them by setting the comment flag in the parsing configuration to true.

Consider the following example. The output of the parser has an additional property, an array named comments. Every element in this array indicates a single-line or a mult-line comment encountered during the parsing process.

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parse('answer = 42 // TODO: why', { comment: true })
  4. Program {
  5. type: 'Program',
  6. body: [ ExpressionStatement { type: 'ExpressionStatement', expression: [Object] } ],
  7. sourceType: 'script',
  8. comments: [ { type: 'Line', value: ' TODO: why' } ] }

The type of each comment can either be Line for a single-line comment (// towards the end-of-line) or Block for a multi-line comment (enclosed by /* and */).

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parse('/*everything*/ answer = 42', { comment: true })
  4. Program {
  5. type: 'Program',
  6. body: [ ExpressionStatement { type: 'ExpressionStatement', expression: [Object] } ],
  7. sourceType: 'script',
  8. comments: [ { type: 'Block', value: 'everything' } ] }

Each comment can also contain its location, if the parsing configuration has the flag range or loc (or both), illustrated here:

  1. $ node
  2. > var esprima = require('esprima')
  3. > output = esprima.parse('answer = 42 // TODO: why', { comment: true, range: true });
  4. > output.comments
  5. [ { type: 'Line', value: ' TODO: why', range: [ 12, 24 ] } ]