This package is a utility that you can use to embed comment nodes inside a
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, as applied by acorn, but does not support the slightly
different non-standard comments made by espree.
When should I use this?
You can use this package when working with comments from Acorn and later working
with a tool such as recast or Babel.
Install
This package is ESM only.
In Node.js (version 16+), install with npm:
👉 Note: the lines are added by recast in this case.
And, some of these weird comments are off, but they’re pretty close.
API
This package exports the identifier attachComments.
There is no default export.
attachComments(tree, comments)
Attach semistandard estree comment nodes to the tree.
This mutates the given tree.
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.
comments (Array<EstreeComment>)
— list of comments
Returns
Nothing (undefined).
Types
This package is fully typed with TypeScript.
It exports no additional types.
Compatibility
Projects maintained by the unified collective are compatible with maintained
versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line,
estree-util-attach-comments@^3, compatible with Node.js 16.