Analyzing TypeScript AST to Track API Usage and Build a Visualized Plugin
This article explains how to convert TypeScript source code into an AST, traverse it to collect import statements, distinguish various import forms, and use the TypeScript compiler API to locate identifier symbols, enabling accurate counting of API calls and line numbers for a given dependency.
The author starts by describing the inefficiency of manually searching for third‑party package usage and proposes building a visual platform that automatically gathers import information from TypeScript projects.
By feeding a code snippet to tsCompiler.createSourceFile the source is transformed into an AST . The article shows the generated AST nodes (ImportDeclaration, VariableStatement, IfStatement, FunctionDeclaration) and explains how each node corresponds to the original code.
Using the TypeScript Compiler API, the author demonstrates how to traverse the AST with tsCompiler.forEachChild , identify Identifier nodes, and record the line numbers where a specific API (e.g., cookie ) is called. The result is an object mapping the API name to call count and line numbers.
To handle real files, the article outlines the three main compilation stages: parsing source to an AST, binding symbols, and performing semantic/type checking. It highlights the importance of the Symbol object for distinguishing imported symbols from local variables.
A utility function parseTs(fileName: string) is introduced to create a Program , retrieve the SourceFile (AST) and the TypeChecker . Another function _findImportItems(ast) walks the AST, uses tsCompiler.isImportDeclaration to locate import statements, and extracts detailed information such as import clause positions, named bindings, and aliasing.
The article then discusses challenges like filtering out same‑name imports, avoiding interference from local declarations, and distinguishing chained calls from direct calls. It shows how to compare node pos and end values with the stored import positions to filter out false positives.
Finally, the author combines the import map with the AST and TypeChecker in _dealAST , iterates over identifier nodes, resolves their symbols, and determines whether they refer to the imported API or a local variable, allowing accurate call counting and further analysis.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.