As we know, when working on bit projects that requires a lot of components and modules to be imported. By time this gets pretty messy and unreadable, and it is really annoying to sort them manually. Here ESLint come into play, we can enforce our editor to sort imports for us automatically. In this artcile, you’ll learn how configure ESLint to imports for us automatically.
Prerequisites
Installing ESLint
To install ESLint globally:
1npm install -g eslint
or we can install ESLint locally within a project:
1# With NPM2npm install eslint --save-dev3# With YARN4yarn add -D eslint
Next, we need to create an ESLin
t config file file (if you haven’t already):
1npx eslint --init
ESLint Configuration
ESLint comes with built-in import sorting rules and only able to sort variable names inside of multiple-imports. It considers the following to be the same type of import:
1import foo from 'foo';2import { bar } from 'bar';
So, I use eslint-plugin-import. It extends the ESLint import rules and have addional feature like
preventing issues with misspelling of file paths and import names. To install eslint-plugin-import
plugin:
1npm install eslint-plugin-import --save-dev2# With YARN3yarn add -D eslint-plugin-import
No rules are enforced by default. However, we need to configure them manually in ESLint config file:
1//.eslintrc file2{3 .......4 extends: ['plugin:import/recommended'],5 rules: {6 'import/namespace': ['error', { allowComputed: true }],7 'import/order': [8 'error',9 {10 groups: [['index', 'sibling', 'parent', 'internal', 'external', 'builtin']],11 'newlines-between': 'never',12 },13 ],14 }15 ......16}
import/namespace
: will report at the import declaration if there are no exported names found. When imported as a full namespace(i.e. import * as foo from './foo'; foo.bar();)
will report if bar is not exported by./foo
.groups
: sets the order intended for every group.newlines-between
: set to never, no new lines are allowed in the entire import section.
And that’s how one sets up autofixable import sorting with ESLint.
Did you find this useful? Buy me a coffee to give my brain a hug ☕️.
Hope you liked this article. If you did, then share it. It means a lot.🙌 Thanks for reading!