dsherret / ts-morph

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

fixUnusedIdentifiers doesn't work on `js` files #1376

Open EladBezalel opened 1 year ago

EladBezalel commented 1 year ago

Describe the bug

Version: 17.0.1

To Reproduce When using fixUnusedIdentifiers on source of a js file, this error occurs Error: Could not find source file

To reproduce:

import { Project } from 'ts-morph';

const project = new Project();
project.addSourceFilesAtPaths([`src/**/*.{ts,js}`]);

const sources = project.getSourceFiles();

sources.forEach(sourceFile => {
  sourceFile.fixUnusedIdentifiers();
});

i also have src folder with file.js

// file.js
const test = 'test'

When i run this code i get this error:

Error: Could not find source file: '.../test/file.js'.
    at getValidSourceFile (.../node_modules/@ts-morph/common/dist/typescript.js:169206:29)
    ....

Expected behavior Should fix unused identifiers or at least not fail

joshjg commented 1 year ago

For anyone facing this issue or a similar issue involving JS files, apparently you must specify allowJs in the Project constructor - it's not enough for it to be configured in your tsconfig files.

const project = new Project({ compilerOptions: { allowJs: true } });