Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixMissingImports after removing import raised ManipulationError #1342

Open
TisnKu opened this issue Oct 19, 2022 · 0 comments
Open

fixMissingImports after removing import raised ManipulationError #1342

TisnKu opened this issue Oct 19, 2022 · 0 comments

Comments

@TisnKu
Copy link

TisnKu commented Oct 19, 2022

Describe the bug
I want to remove some invalid imports caused by code move and reimport from the new correct modules. Removing imports and fixMissingImports both works itself but combining them together would raise manipulation error in the following case.

Error:
Manipulation error: Error replacing tree: The children of the old and new trees were expected to have the same count (2:4).
image

Version: 12.2.0

To Reproduce

import { Project } from "ts-morph";

const project = new Project();
project.createSourceFile(
  "service.ts",
  `
export const a = 100;
`
);
project.createSourceFile(
  "service.interface.ts",
  `
export interface IA {}

export class ClassB {
  public errorCode: string;
}
`
);
project.createSourceFile(
  "service.mock.ts",
  `
import {
  IA,
} from "./service.interface";
import { ClassB } from "./service";

export class ClassC extends ClassB {}
export class ClassA implements IA {}
`
);

const queue = [];
project.getSourceFiles().forEach((sourceFile) => {
  return sourceFile.getImportDeclarations().forEach((declaration) => {
    declaration.getNamedImports().forEach((namedImport) => {
      if (!declaration.getModuleSpecifierValue().startsWith(".")) {
        return;
      }
      const sourceFileImported = declaration.getModuleSpecifierSourceFile();
      if (
        sourceFileImported === undefined ||
        !hasNamedExport(sourceFileImported, namedImport.getName())
      ) {
        queue.push(() => {
          namedImport.remove();
          if (declaration.getNamedImports().length === 0) {
            declaration.remove();
          }
          declaration.getSourceFile().fixMissingImports();
          return declaration.getSourceFile().getFilePath();
        });
      }
    });
  });
});

const optimizedFiles = queue.map((fn) => fn());
project.saveSync();

console.log(optimizedFiles.join("\n"));

function hasNamedExport(sourceFile, namedExport: string): boolean {
  return [...sourceFile.getExportedDeclarations().keys()].some(
    (name: string) => name === namedExport
  );
}

Expected behavior

It should work the same as I execute remove imports and fixMissingImports separately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant