Discover which references are yet to be resolved within a tsx file

I have been tasked with developing a custom builder for a web application. The challenge now is to automatically detect imports in the code so that the right modules can be imported.

My current solution involves traversing the AST of the scripts, keeping track of declared identifiers in the current scope, and then identifying unresolved identifiers. However, this approach requires extensive handling of different types of AST-elements.

Given that both tsc and the TypeScript background server have built-in capabilities for this, I am curious to know how they achieve it, or where in the codebase this feature is implemented. Unfortunately, I have not been able to locate the specific piece of code responsible for this.

Any insights would be greatly appreciated.

Thank you,

Luca

Answer №1

After encountering challenges with utilizing the AST to address certain cases, I managed to find a somewhat unconventional solution. Deciding which identifiers are valid for the current scope proved to be difficult, so I turned to the typescript compiler for error messages.

By filtering and parsing these error messages, I was able to extract identifier names. While this method may not be elegant, it effectively serves its purpose. Additionally, I observed that source file objects containing errors also include exported identifiers, which I accessed directly through the AST.

let compilerHost = {
    // Compiler host properties
};

let unresolved = []
// Creating source file and program
let sourceFile = TS.createSourceFile(filepath, tsCode, TS.ScriptTarget.ES5, true, TS.ScriptKind.TSX);
let program = TS.createProgram([filepath], tsCompilerOptions, compilerHost);
let semanticDiagnostic = program.getSemanticDiagnostics();
if(semanticDiagnostic.length){
    unresolved = <string[]>semanticDiagnostic
        // Filtering for unresolved names
        .filter(m=>m.code == 2304 && m.file == this.sourceFile)
        .map(m=>{
            let matches = (m.messageText as string).match(/^Cannot find name '([A-Z]\w+)'.$/)
            if(matches){
                return matches[1];
            }
        })
        .filter(sym=>typeof(sym)=="string");
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Following an update, the functioning of Visual Studio Tools for Apache Cordova ceases to operate accurately

Currently working on an ionic application using Visual Studio Tools for Apache Cordova, everything was going smoothly until I decided to update the Tools for Apache Cordova and TypeScript Tools for Visual Studio. Following the update, the Ripple emulator s ...

Troubleshooting the Hover Effect of Buttons in Next.js when Using Tailwind CSS for Dynamic Color Changes

Encountering a problem with button hover functionality in a Next.js component using Tailwind CSS. The objective is to alter the button's background color dynamically on hover based on a color value stored in the component's state. This code func ...

Switch over to TypeScript - combining Socket.IO, Angular, and Node.js

This is the code I'm using for my node server: import http from 'http'; import Debug from 'debug'; import socketio, { Server } from 'socket.io'; import app from './app'; import ServerGlobal from './serve ...

Error encountered: The term 'interface' is a restricted keyword

I am in the process of developing a NodeJS and MongoDB library for performing CRUD operations on APIs. My goal is to establish an interface with Typescript that includes the url and database name, structured as follows: However, I am encountering this par ...

How to declare and initialize a variable in Angular 2 using TypeScript

I'm currently working with angular 2 and I'm having trouble understanding how to set a variable. The variable _isLoading is being set in "this.observable.filter((event)" but it doesn't seem to change in the template. This is my TypeScript co ...

Zero's JSON Journey

When I make an HTTP request to a JSON server and store the value in a variable, using console.log() displays all the information from the JSON. However, when I try to use interpolation to display this information in the template, it throws the following er ...

Guide to invoking an API in Next.js 13 by utilizing specific variables within a client component

I currently have a collection of products that are accessible on my website through a straightforward function within a server component. async function getData() { const res = await fetch(`${apiPath}`); const data = (await res.json()) as PackProps ...

Next.js React Server Components Problem - "ReactServerComponentsIssue"

Currently grappling with an issue while implementing React Server Components in my Next.js project. The specific error message I'm facing is as follows: Failed to compile ./src\app\components\projects\slider.js ReactServerComponent ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

An optional field has been identified as ng-invalid

In my set-up, I have created a form group using reactive forms. this.transactionForm = fb.group ({ 'location': [null, Validators.required], 'shopper': [null], 'giftMessage': [null], 'retailPrice& ...

Error: The function $.cookie() is not defined in Angular2 Typescript

After installing @types/jquery, I updated tsconfig.json to include jquery.cookie in the types section. Visual Studio Code indicates that $.cookie is ready for use, but when I execute my code, an error appears in the console stating that $.cookie() is not ...

Error in VS Code related to Vue Array Prop JSDoc TypeScript: The properties of type 'ArrayConstructor' are not found in type 'MyCustomType[]'

After reading the article "Why I no longer use TypeScript with React and why you might want to switch too", I decided to work on a Vue CLI project using ES6 without TypeScript. Instead, I enabled type checking in Visual Studio Code by utilizing JSDoc / @ty ...

Placeholder for Images in Next.js with Typescript

Recently, I've been exploring Next.js with TypeScript and trying to utilize the image component with the placeholder prop. Unfortunately, I keep encountering an error in my implementation. https://i.sstatic.net/rJpbB.png Take a look at my code below ...

Adjust the background color of the header as you scroll

Seeking assistance in adjusting the background color of my header upon scrolling. This is my current implementation: header.component.ts export class HeaderComponent { ngOnInit(): void { const header = document.querySelector('.header'); ...

When the value of a react state is used as the true value in a ternary operator in Types

Attempting to implement sorting on a table is resulting in the following error: (property) direction?: "asc" | "desc" No overload matches this call. Overload 1 of 3, '(props: { href: string; } & { active?: boolean; direction? ...

"Enhance user experience with Angular Material: Popup Windows that preserve functionality in the original window while staying vibrant and accessible

Exploring Angular Material Dialog and other Popup Window Components for a project. Making progress but facing some challenges. Here are the requirements: a) The original screen should not be grayed out, b) Users should be able to interact with the windo ...

Potential absence of the object has been detected after performing object verification

I encountered an issue with the following error message: Object is possibly 'undefined'.ts(2532) This is what my configuration looks like: export interface IDataColumns { name: string; label: string; display: string; empty: boolean; fi ...

Discovering a specific property of an object within an array using Typescript

My task involves retrieving an employer's ID based on their name from a list of employers. The function below is used to fetch the list of employers from another API. getEmployers(): void { this.employersService.getEmployers().subscribe((employer ...

What is the method for accessing the string value of a component's input attribute binding in Angular 2?

In my Angular2 application, I have a straightforward form input component with an @Input binding pointing to the attribute [dataProperty]. The [dataProperty] attribute holds a string value of this format: [dataProperty]="modelObject.childObj.prop". The mod ...

Exploring the potential of utilizing arguments within the RxJS/map operator

When working with rxjs, export function map<T, R, A>(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction<T, R>; I seem to be struggling to find a practical use for thisArg: A. ...