ESLint sort-imports versus VS Code

Don’t get me wrong, both VS Code and ESLint are great tools, but sometimes they do not play nice together. Both have plugins, which are extending their functionality, and sometimes those plugins goes againts each other.

One of such cases is ESLint and automatic sorting of imports in Typescript files.

You can instruct VS Code to sort imports for you on file save, but this option conflicts with similar option in ESLint. It seems to me, that there is simply too many options, and nobody is able to test all combinations. So some combinations result in unexpected behaviour, which may be hard to reproduce, because developers are using different IDEs with different plugins and settings.

Technical details

This VSCode’s settings.json may go against ESLint. See the rule editor.codeActionsOnSave / source.organizeImports. When you are using ESLint, then you may need to turn it OFF.

Beware of source.organizeImports

My ESLint rules for import/order

The main point is this. I’m explicitly setting the groups property, even when it has the default values, because then I can be sure, what the value actually is. Notice also the the alphabetize settings.

"plugins": ["@nrwl/nx", "import"],
//
// and then later:
// 
"import/order": ["error", {
					"groups": ["index", "sibling", "parent", "internal", "external", "builtin", "object", "type"],
					"alphabetize": {
						"order": "asc", /* sort in ascending order. Options: ['ignore', 'asc', 'desc'] */
						"caseInsensitive": true /* ignore case. Options: [true, false] */
					}
				}],

Also I have a Husky pre-commit hook together with lint-staged, which is configured to autofix all eslint problems it founds. Because of lint-staged it checks only the files, which were actually modified, and would be included in the next commit. Here is a nice article explaing why you would like to have such a setup.

For the full example of how to configure .eslintrc file please refer the official documentation.