Remove unused and reorder imports

21 January 2022
With ESLint and VS Code
react-native typescript

Today, I revisited the react-native project that was developed and published by me earlier and the first thing I did was to run tests because I intended to add more Typescript support to the project, wanted to know the current state of test suites of the project.

It wasn't the best FIRST task as a start, but in my opinion, adding more Typescript will be benefiting over the long run.

I've identified removing unused imports to be the low hanging fruit to fix the tsc errors.

I started with https://www.npmjs.com/package/eslint-plugin-unused-imports but turned out it also removes custom Types import that was used in my files.

Then I found out that VS Code can achieve that with organize import feature.

"editor.formatOnSave": true,
"[typescript]": {
    "editor.codeActionsOnSave": {
        "source.organizeImports": true
    }
}

That works also with Shift + Option + o shortcut. However, that will also reorder the imports alphabetically. It seems like there is no way to only remove unused imports without reorder them with organizeImports, that being one issue. The second issue is that I need to also press the shortcut keys for every files. Which is very repetitive work, because there are 1105 files in my /src directory.

$ find src -type f | wc -l
  1105

The second issue was resolved with a VS Code extension to run organizeImports in a folder.

https://marketplace.visualstudio.com/items?itemName=bierner.folder-source-actions

Then to reorder the imports to my desired orders, I found this great article https://dev.to/otamnitram/sorting-your-imports-correctly-in-react-213m that does that.

This is my config

"import/order": [
  "error",
  {
    "groups": [ "builtin", "external", "internal", ["parent", "sibling"] ],
    "pathGroups": [
      {
        "pattern": "react+(|-*)",
        "group": "external",
        "position": "before"
      },
      {
        "pattern": "@**+(/**)",
        "group": "internal",
        "position": "before"
      }
    ],
    "pathGroupsExcludedImportTypes": ["react"],
    "newlines-between": "always",
    "alphabetize": {
      "order": "asc",
      "caseInsensitive": true
    }
  }
],

Just a TIL from me. That's it! Hope it helps.

Cheers.