Organized import statements enhance readability and maintainability in any codebase. ESLint helps enforce these patterns, but for automatic fixes, you’ll need an additional plugin. This guide walks through setting up and configuring ESLint for auto-sorting imports.
Step-by-Step Guide
1. Set ESLint Sort Import Rule (Built-in)
Add the following to your ESLint config:
"rules": {
"sort-imports": ["error", {
"ignoreCase": false,
"ignoreDeclarationSort": false,
"ignoreMemberSort": false,
"memberSyntaxSortOrder": ["none", "all", "multiple", "single"],
"allowSeparatedGroups": false
}]
}
Note: This rule enforces sorted imports but does not auto-fix them.
2. Install Auto-Fix Plugin
To enable automatic fixing, install the eslint-plugin-sort-imports-es6-autofix
package:
npm install eslint-plugin-sort-imports-es6-autofix --save-dev
3. Update ESLint Configuration
Add Plugin
"plugins": ["sort-imports-es6-autofix"]
Add/Replace Rule
"rules": {
"sort-imports-es6-autofix/sort-imports-es6": [2, {
"ignoreCase": false,
"ignoreMemberSort": false,
"memberSyntaxSortOrder": ["none", "all", "multiple", "single"]
}]
}
Rule Explanation
Severity Level
0
– off
1
– warning
2
– error (used in our config)
Options Breakdown
Option | Value | Description |
ignoreCase | false | Sorts imports case-sensitively (A before a ). |
ignoreMemberSort | false | Also sorts named imports alphabetically. |
memberSyntaxSortOrder | [...] | Defines the order of import styles: |
Order Explanation:
"none"
– Side-effect only imports
import 'module';
"all"
– Import everything
import * as name from 'module';
"multiple"
– Multiple named imports
import { a, b } from 'module';
"single"
– Single named import
import { a } from 'module';
Fix Lint Errors Automatically
Run the following command to auto-fix lint issues, including unsorted imports:
npx eslint . --fix
Additional Resources
To add any other ESLint rule, refer to the documentation above.
Summary
Using ESLint with the sort-imports-es6-autofix
plugin helps you:
- Enforce consistent and logical import ordering
- Automatically fix unsorted imports
- Improve code quality in large projects
This setup ensures your codebase stays clean, predictable, and easy to read.