typescript : trigger "organizeImports" from command line

Viewed 3213

VSCode has an editor feature, which allows to clean and order imports in javascript and typescript files on saving ( "source.organizeImports": true ).

Question

How can I call this action on a file from the command line ?

something like :

tslint --fix [apply ordered-imports rule] file1 file2

but it seems tslint has its own implementation for "ordered-imports"

What I gathered so far

From what I understood, this feature triggers a call to the organizeImports function in typescript's codebase.

This functionnality is part of typescript's Language Service, but I don't know how to start a language service daemon, and how to interact with it.

Since the code is written in that function, there also probably is a way to call it synchronously from a ts script, but I couldn't find an example of how to setup the objects and variables from scratch to feed them to this function.

2 Answers

You can try to use Husky for this.

We've setup pre-commit hooks for this like so

  "husky": {
    "hooks": {
      "pre-commit": "tslint -p tsconfig.json"
    }
  }

You can use set such rules on all git hooks

Related