12

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
  • I'm kind of new to VSCode, so I need to ask: What you want to do is to call the organize imports feature from the Command Palette on certain file? or are you talking about how to do it programatically? Commented Jun 6, 2019 at 7:52
  • 2
    I mean : being able to format a file applying the same processing from a shell script (e.g : from a git hook - see stackoverflow.com/questions/56449677 )
    – LeGEC
    Commented Jun 6, 2019 at 7:54

2 Answers 2

8

The organize-imports-cli package does what you want: https://www.npmjs.com/package/organize-imports-cli

-2

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

1
  • 2
    I was looking specifically for typescript's built-in organizeImports action : is there a way to call this from the command line ? You can reach it through vscode "organize imports" action.
    – LeGEC
    Commented Jun 16, 2019 at 21:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.