Tiktok: adding eslint import management was a chore, skip to the bottom and paste that in your eslintrc
Faced with a project that had imports all over the place, I reached for eslint-plugin-import
and thought that would be the end of it…
It doesn’t do as much as I expected
I expected to be able to force usage of aliases instead of relative paths in my imports, but the no-relative-packages
rule did exactly what it said and only forced absolute packages, not modules etc. I had to add the native eslint rule no-restricted-imports
and specify glob patterns that would match relative import paths.
Everything included, I ended up upserting my eslintrc like this:
{
parser: '@typescript-eslint/parser',
extends: ['plugin:import/typescript'],
settings: {
'import/resolver': {
typescript: {
alwaysTryTypes: true,
},
},
},
rules: {
'import/order': ['error', { 'newlines-between': 'never' }],
'import/no-relative-packages': 'error',
'no-restricted-imports': ['error', { patterns: ['./*', '../*'] }],
},
}
Why go through the trouble in the first place?
- A lack of import order enforcing can lead to avoidable git conflicts when 2 different pull requests add imports to the same file (new imports tend to be added after all other imports).
- Empty lines between import statements are fundamentally arbitrary and can lead to avoidable diffs if your editor is set up to automatically add/remove imports depending on your usage in the file.
- Relative imports will always break when moving a file deeper into or out of a folder hierarchy.