How to Auto-Fix and Enforce Sorted Imports Using ESLint

posted 1 min read

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:

  1. "none" – Side-effect only imports
    import 'module';
  2. "all" – Import everything
    import * as name from 'module';
  3. "multiple" – Multiple named imports
    import { a, b } from 'module';
  4. "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.


If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Angular resource() and rxResource() APIs: what you need to know

Davide Passafaro - Mar 24

Smart Contract Bug: Reentrancy Attacks and How to Fix Them

Web3Dev - Feb 19

How to Search in VS Code Faster Using Regex (With Examples)

Opeyemi Ogunsanya - May 18

How Open Source is Shaping My Journey as a Developer

Anuj Kumar Sharma - Jan 7

create a custom schematic to do things like cleaning up unused imports in a web application

Sunny - Jul 4
chevron_left