dsherret / ts-morph

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

Removing the last named export creates a star export #1551

Open kosciolek opened 1 week ago

kosciolek commented 1 week ago

Describe the bug

Version: 23.0.0

Calling namedExport.remove() on the last named export in a declaration inserts an export * from 'module'; , instead of removing the declaration.

To Reproduce

import { Project } from "ts-morph";

(async () => {
  const project = new Project();

  project.addSourceFileAtPath("test.ts");

  for (const file of project.getSourceFiles()) {
    for (const declaration of file.getExportDeclarations()) {
      for (const namedExport of declaration.getNamedExports()) {
        namedExport.remove();
      }
    }
  }

  await project.save();
})();

Input:

export { a } from "./b";

Output:

export * from "./b";

Expected behavior

An empty file (the export declaration should be simply removed).

kosciolek commented 1 week ago

I can contribute a bugfix, if someone confirms this really is a bug and not intended

dsherret commented 1 week ago

It should go to:

export { } from "./b";

Someone may go to add a named export after removing the last one.

kosciolek commented 1 week ago

@dsherret I believe there should be 2 methods then, since this behavior is easy to miss remove and removeAndRemoveDeclarationIfEmpty, or removeWithDeclaration

WDYT?

dsherret commented 1 week ago

There's already an exportDeclaration.remove(). I don't think we need so many methods.