dsherret / ts-morph

TypeScript Compiler API wrapper for static analysis and programmatic code changes.
https://ts-morph.com
MIT License
5k stars 195 forks source link

.tsx files do not return referencing SourceFiles #1250

Open brandongregoryscott opened 2 years ago

brandongregoryscott commented 2 years ago

Describe the bug

Version: 13.0.2

I believe this is a bug, but I'm not 100% sure. I'm getting results from SourceFile.getReferencingSourceFiles() as well as SourceFile.getReferencingNodesInOtherSourceFiles() when running some of my code through an actual (persisted on disk) TypeScript project, but not when writing unit tests with an in-memory file system.

I'm not able to put this code in a CodeSandbox environment - it keeps freezing, I'm assuming there's some missing API/system access attempt locking up the sandbox UI, but this code sample should be a very simple example of what I'm trying to do.

To Reproduce

import {
    Project,
    VariableDeclarationKind,
} from "ts-morph";

const project = new Project();
const file1 = project.createSourceFile("file1.tsx");

file1.addVariableStatement({
  declarationKind: VariableDeclarationKind.Const,
  declarations: [{ name: "example", initializer: "5" }],
});

file1.addExportDeclaration({
  namedExports: ["example"],
});

const file2 = project.createSourceFile(
  "file2.tsx",
    `
        console.log("example", example);
    `
);

file2.addImportDeclaration({
  namedImports: ["example"],
  moduleSpecifier: file2.getRelativePathAsModuleSpecifierTo(file1),
});

console.log(file1.getReferencingSourceFiles());
expect(file1.getReferencingSourceFiles()).toContain(file2);

Expected behavior

file1.getReferencingSourceFiles() should return an array containing file2 since it imports a node from it.

EDIT: After some further testing, I narrowed it down to the files being created with a .tsx extension, not .ts, and I don't think it's related to being an in-memory filesystem or not. I updated the example to reflect this.

webpro commented 2 years ago

Not sure if it's the same cause, but had a similar issue wondering why imported *.tsx files were not added to the project. This solved it for me:

const project = new Project({
  compilerOptions: {
    jsx: ts.JsxEmit.ReactJSX
  }
});

Somewhere deep in typescript.js it does getResolutionDiagnostic for each module using needJsx().

molszanski commented 2 years ago

@webpro I think I am having this nested issue with knip