2.6.12 • Published 6 years ago

typescript-walk v2.6.12

Weekly downloads
3
License
ISC
Repository
github
Last release
6 years ago

typescript-walk

Simple package for traversing typescript AST nodes.

This package version will be inferred from typescript package version. For example typescript 2.6.1 will generate 2.6.1# where # is this package revision number - 2.6.10, 2.6.142 for example

Installation

$ npm install typescript-walk

API

visit (node: ts.Node, visitor: Visitor) => void;

Main function of this package. Requires typescript AST node and instance of Visitor object.

Visitor

Helper type describing Visitor object used for visiting AST nodes.

Example

import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import { visit, Visitor } from './index';

// visitor class
class MyVisitor implements Visitor {
  // do whatever u need ...
  readonly kinds: string[];
  constructor() {
    this.kinds = [];
  }

  // default handler - called in case of undeclared handler
  Default(node: ts.Node) {
    this.kinds.push(ts.SyntaxKind[node.kind]);
  }

  // handler for ts.SyntaxKind.Block
  Block(_: ts.Block) {
    this.kinds.push('BLOCK');
  }

  // handler for ts.SyntaxKind.Expression
  Expression(_: ts.Expression): false {
    this.kinds.push('EXPRESSION');
    // skips traversin children
    return false;
  }
}

// load & parse file
const fileName: string = ...
const sourceFile = ts.createSourceFile(
  fileName,
  fs.readFileSync(fileName, 'utf8'),
  ts.ScriptTarget.Latest,
  true,
);

// walk AST
const visitor = new MyVisitor();
visit(sourceFile, visitor);

// show results
console.log(visitor.kinds.join('\n'));