How to config VSCode's Organize Imports order?
Asked Answered
R

1

34

I want to config Organize Imports's order.

Right now, it moves node_modules related import statement at the very top, and local ts file at very bottom:

Normal:

import myFunction from './myFunction';
import fs from 'fs';

console.log(fs)
console.log(myFunction)

After running Organize Imports command:

import fs from 'fs';
import myFunction from './myFunction';

console.log(fs)
console.log(myFunction)

What I want to do is reverse the order, I want node_modules to be very bottom, local imports to be very top.

How can I achieve this behaviour?

Receiver answered 5/6, 2019 at 9:7 Comment(2)
I am not familiar with the Organize Imports at all, but quick read-through of marketplace.visualstudio.com/… indicates that you will need to define your groups such that you have relative and relativeDirect higher in the array.Keijo
See https://mcmap.net/q/451875/-visual-studio-code-organize-imports-feature for "group-aware Organize Imports" and github.com/microsoft/vscode-docs/blob/vnext/release-notes/….Adsorbent
F
40

The built-in "Organize Imports" functionality has no configuration, according to the documentation.

You can customize import ordering using a third-party extension, such as alfnielsen.vsc-organize-imports or by using a separate linting tool like eslint or tslint.

In eslint (my recommendation, since tslint has been deprecated), you'll need to also use a plugin like eslint-plugin-import to get the more-specific configuration you want. Then, instead of using the VSCode "Organize Imports" action, you'll use the "Fix All" action or a invoke a quick fix.

Here's a partial example .eslint.js config file.

module.exports = {
  plugins: [
    "import",
  ],
  rules: {
    "import/order": [
      "error",
      {
        groups: [
          "index",
          "sibling",
          "parent",
          "internal",
          "external",
          "builtin"
        ]
      }
    ]
  }
}
Foulup answered 31/3, 2020 at 8:55 Comment(1)
the order is opposite, it should be groups: ["builtin", "external", "internal", "parent", "sibling", "index", "object"]Enosis

© 2022 - 2024 — McMap. All rights reserved.