eslint-plugin-perfectionist

repository·main·Indexed 25 days ago

https://github.com/azat-io/eslint-plugin-perfectionist

An ESLint plugin that enforces consistent code formatting by sorting data structures—including imports, objects, TypeScript types, enums, and JSX props—alphabetically, naturally, or by line length. All rules are automatically fixable. It provides pre-defined configurations such as recommended-alphabetical, recommended-natural, and recommended-line-length, as well as an Alphabet class for creating custom sorting orders.

Tokens
53.2K
Snippets
131
Records
244
Agent score
80%

What's inside eslint-plugin-perfectionist

  1. Configure the perfectionist/sort-modules rule

    main

    The perfectionist/sort-modules rule sorts module imports and exports. It was introduced in version v4.0.0. You can configure it using either ESLint Flat Config or Legacy Config formats.

    // Flat Config (eslint.config.js)
    import perfectionist from 'eslint-plugin-perfectionist'
    
    export default [
      {
        plugins: {
          perfectionist,
        },
        rules: {
          'perfectionist/sort-modules': [
            'error',
            {
              type: 'alphabetical',
              order: 'asc',
              fallbackSort: { type: 'unsorted' },
              ignoreCase: true,
              specialCharacters: 'keep',
              partitionByComment: false,
              partitionByNewLine: false,
              newlinesBetween: 'ignore',
              newlinesInside: 'ignore',
              groups: [
                'declare-enum',
                'export-enum',
                'enum',
                ['declare-interface', 'declare-type'],
                ['export-interface', 'export-type'],
                ['interface', 'type'],
                'declare-class',
                'class',
                'export-class',
                'declare-function',
                'export-function',
                'function'
              ],
              customGroups: [],
              useExperimentalDependencyDetection: true,
            },
          ],
        },
      },
    ]
  2. Use the sort-variable-declarations rule

    main

    The sort-variable-declarations rule enforces a consistent order of variable declarations within a scope. This helps improve code readability and maintainability by providing a predictable structure for variables in functions or modules.

    Supported sorting strategies include:

    • Alphabetical: Sorting variables by their name.
    • Line Length: Sorting variables based on the length of their declaration line.
    • Initial: Maintaining the original order (used as a fallback or baseline).
    // Example of alphabetical sorting
    const API_KEY = 'e7c3b6d4-7b7d-4b3b-8b3b-7b3b7b3b7b3b',
          apiUrl = 'https://api.perfectionist.dev',
          data = fetchData(),
          isAuthenticated = checkAuth(),
          user = getCurrentUser()
    
    const config = loadConfig(),
          database = connectToDatabase(),
          environment = process.env.NODE_ENV,
          logger = createLogger(),
          server = createServer()
  3. Use the recommended-natural configuration

    main

    The recommended-natural configuration enables all eslint-plugin-perfectionist rules using natural sorting in ascending order. Unlike alphabetical sorting, natural sorting handles strings containing both letters and numbers intuitively (e.g., item-1, item-2, item-10). This is ideal for version files, task lists, or datasets where numerical values are present and human-readable order is preferred.

    // Flat Config (eslint.config.js)
    import perfectionist from 'eslint-plugin-perfectionist'
    
    export default [
      perfectionist.configs['recommended-natural'],
    ]
  4. Install eslint-plugin-perfectionist

    main

    To use this plugin, you must first install ESLint v8.45.0 or greater, followed by the perfectionist plugin.

    npm install --save-dev eslint
    npm install --save-dev eslint-plugin-perfectionist
    npm install --save-dev eslint
    npm install --save-dev eslint-plugin-perfectionist
  5. Sort TypeScript enum members with sort-enums

    main

    The sort-enums rule enforces a consistent and predictable order for TypeScript enum members. This improves code readability and makes it easier to identify missing or duplicate entries. The rule can sort enums alphabetically or by line length.

    enum Priority {
      Critical = 'Critical',
      High = 'High',
      Low = 'Low',
      Medium = 'Medium',
      None = 'None',
    }
    
    enum Status {
      Cancelled = 'Cancelled',
      Completed = 'Completed',
      InProgress = 'In Progress',
      NotStarted = 'Not Started',
      OnHold = 'On Hold',
    }
  6. Configure the sort-exports rule

    main

    The perfectionist/sort-exports rule enforces a consistent order for exported members. You can configure it using either ESLint Flat Config or Legacy Config.

    Common configuration options include:

    • type: The sorting strategy (e.g., 'alphabetical').
    • order: The direction of sorting ('asc' or 'desc').
    • fallbackSort: Defines how to handle items that don't fit the primary sorting strategy.
    • ignoreCase: Boolean to determine if case should be ignored during sorting.
    • specialCharacters: How to handle special characters (e.g., 'keep').
    • partitionByComment: Whether to group exports by comments.
    • partitionByNewLine: Whether to group exports by new lines.
    • newlinesBetween: Controls newlines between sorted items.
    // Flat Config (eslint.config.js)
    import perfectionist from 'eslint-plugin-perfectionist'
    
    export default [
      {
        plugins: {
          perfectionist,
        },
        rules: {
          'perfectionist/sort-exports': [
            'error',
            {
              type: 'alphabetical',
              order: 'asc',
              fallbackSort: { type: 'unsorted' },
              ignoreCase: true,
              specialCharacters: 'keep',
              partitionByComment: false,
              partitionByNewLine: false,
              newlinesBetween: 'ignore',
              newlinesInside: 'ignore',
              groups: [],
              customGroups: [],
            },
          ],
        },
      },
    ]
  7. Configure perfectionist/sort-modules via Legacy Config

    main

    For projects using the legacy .eslintrc.js format, add perfectionist to the plugins array and configure the perfectionist/sort-modules rule in the rules object.

    // .eslintrc.js
    module.exports = {
      plugins: [
        'perfectionist',
      ],
      rules: {
        'perfectionist/sort-modules': [
          'error',
          {
            type: 'alphabetical',
            order: 'asc',
            fallbackSort: { type: 'unsorted' },
            ignoreCase: true,
            specialCharacters: 'keep',
            partitionByComment: false,
            partitionByNewLine: false,
            newlinesBetween: 'ignore',
            newlinesInside: 'ignore',
            groups: [
              'declare-enum',
              'export-enum',
              'enum',
              ['declare-interface', 'declare-type'],
              ['export-interface', 'export-type'],
              ['interface', 'type'],
              'declare-class',
              'class',
              'export-class',
              'declare-function',
              'export-function',
              'function'
            ],
            customGroups: [],
            useExperimentalDependencyDetection: true,
          },
        ],
      },
    }
  8. Use the sort-named-imports rule

    main

    The sort-named-imports rule enforces a standardized ordering of named imports to improve code readability and navigation. It allows you to sort imports either alphabetically or by line length.

    Important: If you are using the standard ESLint sort-imports rule, you should disable it to prevent conflicts with this rule.

    // Example of sorted named imports (alphabetical)
    import {
      createContext,
      useEffect,
      useId,
      useLayoutEffect,
      useReducer,
      useRef,
      useState,
    } from 'react'
    
    import {
      createBrowserRouter,
      Link,
      Route,
      RouterProvider,
    } from 'react-router-dom'
    
    import { useDispatch, useStore } from 'react-redux'