2

In vscode, there is option to remove unused imports, add all missing imports, and prettify (ALT + SHIFT +f).

I have files generator, and i wont to do all this stuff via code

David Sherret
  • 101,669
  • 28
  • 188
  • 178
yantrab
  • 2,482
  • 4
  • 31
  • 52

1 Answers1

4

This is possible with my library ts-morph. Here's some sample code that does this for every file associated with a tsconfig.json:

import { Project } from "ts-morph";

const project = new Project({ tsConfigFilePath: "tsconfig.json" });

for (const sourceFile of project.getSourceFiles()) {
    sourceFile.fixMissingImports()
        .organizeImports()
        .fixUnusedIdentifiers()
        .formatText();
}

project.save().then(() => console.log("done"));

All of these methods accept arguments for specifying how formatting should be done (limited by the configurations available in the compiler API).

David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • thanks, i already using your awesome library. but don't know that it is possible . thanks! – yantrab Mar 29 '19 at 05:46
  • It is not remove my unused const data = require('.data.json'); – yantrab Mar 29 '19 at 08:17
  • @yantrab I updated the answer to include variable declarations. – David Sherret Mar 29 '19 at 13:21
  • @yantrab in ts-morph 2.0 there is a new `fixUnusedIdentifiers()` method you can use to remove unused identifiers. Note: You may need to call that multiple times if there are unused identifiers that referenced identifiers that were removed. See an example of dealing with that [here](https://github.com/dsherret/ts-morph/issues/590#issuecomment-479285956). – David Sherret Apr 20 '19 at 23:23