print-highlighted-ast
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

print-highlighted-ast

CircleCI Coverage Status semantic-release Commitizen friendly npm version

print a babel AST with specific nodes highlighted, for debugging codemods

Example

Script

import printHighlightedAst from 'print-highlighted-ast'
import { parse } from '@babel/parser'
import traverse, { NodePath } from '@babel/traverse'
import chalk from 'chalk'
 
const code = `
const foo = () => 2
const bar = 500 + 600
`
const ast = parse(code)
const highlights: Array<[NodePath<any>, (code: string) => string]> = []
traverse(ast, {
  NumericLiteral: path => {
    highlights.push([path, chalk.bgBlue])
  },
})
 
console.log(printHighlightedAst(code, { highlights })

Output

const foo = () => 2
const bar = 500 + 600

API

You can pass the source code or a parsed AST as the first argument. If you pass an AST it will be converted to code with @babel/generator.

Each element of highlights is a tuple of [0] path you want to highlight, [1] highlighting function. You can pass options to @babel/parser and @babel/generator as shown below.

The code will be parsed with @babel/parser to determine the source range of the paths you want to highlight. If you're using language extensions like Flow, Typescript, or JSX, you'll need to pass those plugins in parseOptions.

import { Node } from '@babel/types'
import { NodePath } from '@babel/traverse'
import generate from '@babel/generator'
import { parse } from '@babel/parser'
 
function printHighlightedAst(
  codeOrAst: string | Node,
  {
    highlights,
    generateOptions,
    parseOptions,
  }: {
    highlights: Iterable<[NodePath<any>, (code: string) => string]>
    generateOptions?: Parameters<typeof generate>[1]
    parseOptions?: Parameters<typeof parse>[1]
  }
): string

/print-highlighted-ast/

    Package Sidebar

    Install

    npm i print-highlighted-ast

    Weekly Downloads

    0

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    408 kB

    Total Files

    9

    Last publish

    Collaborators

    • jedwards1211