Wondering what’s next for npm?Check out our public roadmap! »

    estree-util-attach-comments
    TypeScript icon, indicating that this package has built-in type declarations

    2.0.0 • Public • Published

    estree-util-attach-comments

    Build Coverage Downloads Size

    Attach semistandard estree comment nodes (such as from espree or 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.

    Install

    This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.

    npm:

    npm install estree-util-attach-comments

    Use

    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'
    
    var comments = []
    var 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.

    API

    This package exports the following identifiers: attachComment. There is no default export.

    attachComment(tree, comments)

    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.

    Returns

    Node — The given tree.

    License

    MIT © Titus Wormer

    Install

    npm i estree-util-attach-comments

    DownloadsWeekly Downloads

    4,461

    Version

    2.0.0

    License

    MIT

    Unpacked Size

    11 kB

    Total Files

    5

    Last publish

    Collaborators

    • avatar
    • avatar