Attach semistandard estree comment nodes (such as from acorn with a couple lines of code) to the nodes in that tree.
This is useful because certain estree parsers give you an array (espree and acorn) whereas other estree tools expect comments to be embedded on nodes in the tree.
This package uses one comments
array where each comment has leading
and trailing
fields.
Note that espree uses slightly different non-standard comments.
This package is ESM only: Node 12+ is needed to use it and it must be import
ed
instead of require
d.
npm:
npm install estree-util-attach-comments
Say we have this weird code
:
/* 1 */ function /* 2 */ a /* 3 */ (/* 4 */b) /* 5 */ { /* 6 */ return /* 7 */ b + /* 8 */ 1 /* 9 */ }
And our script, example.js
, looks as follows:
import * as acorn from 'acorn'
import recast from 'recast'
import {attachComments} from 'estree-util-attach-comments'
const comments = []
const tree = acorn.parse(code, {ecmaVersion: 2020, onComment: comments})
attachComments(tree, comments)
console.log(recast.print(tree).code)
Yields:
/* 1 */
function /* 2 */
a(
/* 3 */
/* 4 */
b
) /* 5 */
{
/* 6 */
return (
/* 7 */
b + /* 8 */
1
);
}/* 9 */
Note that the lines are added by recast
in this case.
And, some of these weird comments are off, but they’re pretty close.
This package exports the following identifiers: attachComments
.
There is no default export.
Attach semistandard estree comment nodes to the tree.
This mutates the given tree
(Program
).
It takes comments
, walks the tree, and adds comments as close as possible
to where they originated.
Comment nodes are given two boolean fields: leading
(true
for /* a */ b
)
and trailing
(true
for a /* b */
).
Both fields are false
for dangling comments: [/* a */]
.
This is what recast
uses too, and is somewhat similar to Babel, which is not
estree but instead uses leadingComments
, trailingComments
, and
innerComments
arrays on nodes.
The algorithm checks any node: even recent (or future) proposals or nonstandard syntax such as JSX, because it ducktypes to find nodes instead of having a list of visitor keys.
The algorithm supports loc
fields (line/column), range
fields (offsets),
and direct start
/ end
fields.
Node
— The given tree
.