Perfectionist

sort-imports

Enforce sorted imports.

Maintaining a consistent and sorted order of imports is crucial for improving code readability and organization.

This rule ensures that imports are easily locatable and quickly scannable, especially in modules with numerous import statements.

By reducing the likelihood of errors caused by import conflicts and providing a clear structure, this rule helps developers manage imports efficiently and maintain a tidy codebase.

Important

If you use the sort-imports rule or the order rule from the eslint-plugin-import plugin, it is highly recommended to disable them to avoid conflicts.

If you use the prettier-plugin-sort-imports plugin, remove them from the prettier config to avoid conflicts.

Rule perfectionist/sort-imports works in a similar way to rule import/order, but with some differences:

  1. Supporting for new import types:
  • 'side-effect'
  • 'style'
  • 'builtin-type'
  • 'internal-type'
  • 'parent-type'
  • 'sibling-type'
  • 'index-type'
  1. Supporting for adding custom import groups
  2. Sorting not only alphabetically, but also naturally and by line length

Try it out

import User from '~/models/User'
import bodyParser from 'body-parser'
import initializePassport from '~/config/passport'
import mongoose from 'mongoose'
import express from 'express'

import type { Response, Request } from 'express'
import passport from 'passport'
import path from 'node:path'
import defaultsDeep from 'lodash/defaultsDeep'
import logger from '~/middleware/logger'

import map from 'lodash/map'

import dbConfig from './db'
import session from 'express-session'
import fs from 'node:fs/promises'
import authRoutes from '~/routes/auth'

Options

This rule accepts an options object with the following properties:

type

default: 'alphabetical'

Specifies the sorting method.

  • 'alphabetical' — Sort items alphabetically (e.g., “a” < “b” < “c”) using localeCompare.
  • 'natural' — Sort items in a natural order (e.g., “item2” < “item10”).
  • 'line-length' — Sort items by code line length (shorter lines first).
  • 'custom' — Sort items using the alphabet specified in the alphabet option.
  • 'unsorted' — Do not sort items. grouping and newlines behavior are still enforced.

order

default: 'asc'

Specifies whether to sort items in ascending or descending order.

  • 'asc' — Sort items in ascending order (A to Z, 1 to 9).
  • 'desc' — Sort items in descending order (Z to A, 9 to 1).

fallbackSort

type:

{
  type: 'alphabetical' | 'natural' | 'line-length' | 'custom' | 'unsorted'
  order?: 'asc' | 'desc'
}
default: { type: 'unsorted' }

Specifies fallback sort options for elements that are equal according to the primary sort type.

Example: enforce alphabetical sort between two elements with the same length.

{
  type: 'line-length',
  order: 'desc',
  fallbackSort: { type: 'alphabetical', order: 'asc' }
}

alphabet

default: ''

Used only when the type option is set to 'custom'. Specifies the custom alphabet for sorting.

Use the Alphabet utility class from eslint-plugin-perfectionist/alphabet to quickly generate a custom alphabet.

Example: 0123456789abcdef...

ignoreCase

default: true

Specifies whether sorting should be case-sensitive.

  • true — Ignore case when sorting alphabetically or naturally (e.g., “A” and “a” are the same).
  • false — Consider case when sorting (e.g., “a” comes before “A”).

specialCharacters

default: keep

Specifies whether to trim, remove, or keep special characters before sorting.

  • 'keep' — Keep special characters when sorting (e.g., “_a” comes before “a”).
  • 'trim' — Trim special characters when sorting alphabetically or naturally (e.g., “_a” and “a” are the same).
  • 'remove' — Remove special characters when sorting (e.g., “/a/b” and “ab” are the same).

locales

default: 'en-US'

Specifies the sorting locales. Refer To String.prototype.localeCompare() - locales.

  • string — A BCP 47 language tag (e.g. 'en', 'en-US', 'zh-CN').
  • string[] — An array of BCP 47 language tags.

internalPattern

default: ['^~/.*']

Specifies a pattern for identifying internal imports. This is useful for distinguishing your own modules from external dependencies.

You can use regexp patterns to define these internal imports.

sortSideEffects

default: false

Specifies whether side effect imports should be sorted. By default, sorting side-effect imports is disabled for security reasons.

  • true — Sort side effect imports.
  • false — Do not sort side effect imports.

partitionByComment

default: false

Enables the use of comments to separate imports into logical groups.

  • true — All comments will be treated as delimiters, creating partitions.
  • false — Comments will not be used as delimiters.
  • RegExpPattern = string | { pattern: string; flags: string} — A regexp pattern to specify which comments should act as delimiters.
  • RegExpPattern[] — A list of regexp patterns to specify which comments should act as delimiters.
  • { block: boolean | RegExpPattern | RegExpPattern[]; line: boolean | RegExpPattern | RegExpPattern[] } — Specify which block and line comments should act as delimiters.

partitionByNewLine

default: false

When true, the rule will not sort imports if there is an empty line between them. This helps maintain the defined order of logically separated groups of members.

import { b1, b2 } from 'b'

import { a } from 'a'
import { c } from 'c'

newlinesBetween

default: 'always'

Specifies how to handle new lines between import groups.

  • ignore — Do not report errors related to new lines between import groups.
  • always — Enforce one new line between each group, and forbid new lines inside a group.
  • never — No new lines are allowed in the entire import section.

You can also enforce the newline behavior between two specific groups through the groups options.

See the groups option.

This option is only applicable when partitionByNewLine is false.

maxLineLength

default: undefined

Specifies a maximum line length for sorting imports. When the line length exceeds this number, sorting will be based only on the import name, excluding the elements.

This option is only available when the type is set to 'line-length'.

tsconfigRootDir

default: undefined

Specifies the directory of the root tsconfig.json file (ex: .). This is used in groups for:

  • Marking aliased imports as internal.
  • Marking imports matching tsconfig paths as tsconfig-path.

groups

type: Array<string | string[]>

default:

[
  'type-import',
  ['value-builtin', 'value-external'],
  'type-internal',
  'value-internal',
  ['type-parent', 'type-sibling', 'type-index'],
  ['value-parent', 'value-sibling', 'value-index'],
  'ts-equals-import',
  'unknown',
]

Specifies a list of import groups for sorting. Groups help organize imports into meaningful categories, making your code more readable and maintainable.

Each import will be assigned a single group specified in the groups option (or the unknown group if no match is found). The order of items in the groups option determines how groups are ordered.

Within a given group, members will be sorted according to the type, order, ignoreCase, etc. options.

Individual groups can be combined together by placing them in an array. The order of groups in that array does not matter. All members of the groups in the array will be sorted together as if they were part of a single group.

Predefined groups are characterized by a single selector and potentially multiple modifiers. You may enter modifiers in any order, but the selector must always come at the end.

Selectors

The list of selectors is sorted from most to least important:

  • 'type' — TypeScript type imports.
  • 'side-effect-style' — Side effect style imports.
  • 'side-effect' — Side effect imports.
  • 'style' — Styles.
  • 'tsconfig-path'tsconfig paths alias imports. Requires tsconfigRootDir to be set.
  • 'index' — Main file from the current directory.
  • 'sibling' — Modules from the same directory.
  • 'parent' — Modules from the parent directory.
  • 'subpath' — Node.js subpath imports.
  • 'internal' — Your internal modules.
  • 'builtin' — Node.js Built-in Modules.
  • 'external' — External modules installed in the project.
  • 'import' — Any import.

Modifiers

The list of modifiers is sorted from most to least important:

  • 'side-effect' — Side effect imports.
  • 'type' — Typescript type imports.
  • 'value' — Value imports.
  • 'ts-equals' — TypeScript import-equals imports.
  • 'require'require imports.
  • 'default' — Imports containing the default specifier.
  • 'wildcard' — Imports containing the wildcard (* as) specifier.
  • 'named' — Imports containing at least one named specifier.

Important notes

The unknown group

Members that don’t fit into any group specified in the groups option will be placed in the unknown group. If the unknown group is not specified in the groups option, the members will remain in their original order.

Behavior when multiple groups match an element

The lists of selectors and modifiers above are both sorted by importance, from most to least important. In case of multiple groups matching an element, the following rules will be applied:

  1. Selector priority: type, index, … will take precedence over external groups for example.
  2. If the selector is the same, the group with the most modifiers matching will be selected.
  3. If modifiers quantity is the same, order will be chosen based on modifier importance as listed above.

Example 1:

import type { FC } from 'react'

react can be matched by the following groups, from most to least important:

  • named-type (type selector).
  • type.
  • named-type-external or type-named-external (type modifier).
  • type-external.
  • named-external.
  • external.
  • named-type-import or type-named-import.
  • type-import.
  • named-import.
  • import.

Example 2:

import 'style.scss'

style.scss can be matched by the following relevant groups, from most to least important:

  • side-effect-style (side-effect-style selector).
  • side-effect.
  • value-style.
  • style.
  • side-effect-import. (side-effect modifier)
  • value-import.
  • import.

Example 3 (The most important group is written in the comments):

// 'value-builtin' - Node.js Built-in Modules
import path from 'path'
// 'value-external' - External modules installed in the project
import axios from 'axios'
// 'value-internal' - Your internal modules
import Button from '~/components/Button'
// 'value-parent' - Modules from parent directory
import formatNumber from '../utils/format-number'
// 'value-subpath' - Node.js subpath imports
import subpathContent from '#subpathModule'
// 'value-sibling' - Modules from the same directory
import config from './config'
// 'value-side-effect' - Side effect imports
import './set-production-env.js'
// value-side-effect-style - Side effect style imports
import './styles.scss'
// 'value-index' - Main file from the current directory
import main from '.'
// 'value-style' - Styles
import styles from './index.module.css'
// 'type-external' - TypeScript type imports
import type { FC } from 'react'
// 'named-type-builtin' - TypeScript type imports from Built-in Modules
import type { Server } from 'http'
// 'named-type-internal' - TypeScript type imports from your internal modules
import type { User } from '~/users'
// 'named-type-parent' - TypeScript type imports from parent directory
import type { InputProps } from '../Input'
// 'named-type-sibling' - TypeScript type imports from the same directory
import type { Details } from './data'
// 'named-type-index' - TypeScript type imports from main directory file
import type { BaseOptions } from './index.d.ts'
// 'value-ts-equals-import' - TypeScript import-equals imports
import NotFoundError = ErrorsNamespace.NotFoundError

Newlines between groups

You may place newlinesBetween objects between your groups to enforce the newline behavior between two specific groups.

See the newlinesBetween option.

This feature is only applicable when partitionByNewLine is false.

{
  newlinesBetween: 'always',
  groups: [
    'a',
    { newlinesBetween: 'never' }, // Overrides the global newlinesBetween option
    'b',
  ]
}

customGroups

Migrating from the old API

Support for the object-based customGroups option is deprecated.

Here is how to migrate from the old to the current API:

Old API:

{
  value: {
    "keyForValue1": "value1",
    "keyForValue2": "value2"
  },
  type: {
    "keyForType1": "value1",
    "keyForType2": "value2"
  }
}

Current API:

[
  {
    "selector": "type",
    "groupName": "keyForType1",
    "elementNamePattern": "value1"
  },
  {
    "selector": "type",
    "groupName": "keyForType2",
    "elementNamePattern": "value2"
  },
  {
    "groupName": "keyForValue1",
    "elementNamePattern": "value1"
  },
  {
    "groupName": "keyForValue2",
    "elementNamePattern": "value2"
  }
]

type: Array<CustomGroupDefinition | CustomGroupAnyOfDefinition>

default: []

You can define your own groups and use regex for matching very specific imports.

A custom group definition may follow one of the two following interfaces:

interface CustomGroupDefinition {
  groupName: string
  type?: 'alphabetical' | 'natural' | 'line-length' | 'unsorted'
  order?: 'asc' | 'desc'
  fallbackSort?: { type: string; order?: 'asc' | 'desc' }
  newlinesInside?: 'always' | 'never'
  selector?: string
  modifiers?: string[]
  elementNamePattern?: string | string[] | { pattern: string; flags?: string } | { pattern: string; flags?: string }[]
}

An import will match a CustomGroupDefinition group if it matches all the filters of the custom group’s definition.

or:

interface CustomGroupAnyOfDefinition {
  groupName: string
  type?: 'alphabetical' | 'natural' | 'line-length' | 'unsorted'
  order?: 'asc' | 'desc'
  fallbackSort?: { type: string; order?: 'asc' | 'desc' }
  newlinesInside?: 'always' | 'never'
  anyOf: Array<{
      selector?: string
      modifiers?: string[]
      elementNamePattern?: string | string[] | { pattern: string; flags?: string } | { pattern: string; flags?: string }[]
  }>
}

An import will match a CustomGroupAnyOfDefinition group if it matches all the filters of at least one of the anyOf items.

Attributes

  • groupName — The group’s name, which needs to be put in the groups option.
  • selector — Filter on the selector of the element.
  • modifiers — Filter on the modifiers of the element. (All the modifiers of the element must be present in that list)
  • elementNamePattern — If entered, will check that the name of the element matches the pattern entered.
  • type — Overrides the type option for that custom group. unsorted will not sort the group.
  • order — Overrides the order option for that custom group.
  • fallbackSort — Overrides the fallbackSort option for that custom group.
  • newlinesInside — Enforces a specific newline behavior between elements of the group.

Match importance

The customGroups list is ordered: The first custom group definition that matches an element will be used.

Custom groups have a higher priority than any predefined group. If you want a predefined group to take precedence over a custom group, you must write a custom group definition that does the same as what the predefined group does (using selector and modifiers filters), and put it first in the list.

Example

   groups: [
+    'react',
     'type-import',
     ['value-builtin', 'value-external'],
+    'lodash',
     'type-internal',
     'value-internal',
     ['type-parent', 'type-sibling', 'type-index'],
     ['value-parent', 'value-sibling', 'value-index'],
     'ts-equals-import',
     'unknown',
   ],
+  customGroups: [                      
+    {                                
+      groupName: 'react',
+      elementNamePattern: ['^react$', '^react-.+'],
+    },
+    {                                 
+      groupName: 'lodash',
+      elementNamePattern: 'lodash',
+    }                               
+  ],
 }

environment

default: 'node'

Specifies which environment’s built-in modules should be recognized. If you are using Bun, change the value to 'bun'.

Usage

// .eslintrc.js
module.exports = {
plugins: [
'perfectionist',
],
rules: {
'perfectionist/sort-imports': [
'error',
{
type: 'alphabetical',
order: 'asc',
fallbackSort: { type: 'unsorted' },
ignoreCase: true,
specialCharacters: 'keep',
internalPattern: ['^~/.+'],
partitionByComment: false,
partitionByNewLine: false,
newlinesBetween: 'always',
maxLineLength: undefined,
groups: [
'type-import',
['value-builtin', 'value-external'],
'type-internal',
'value-internal',
['type-parent', 'type-sibling', 'type-index'],
['value-parent', 'value-sibling', 'value-index'],
'ts-equals-import',
'unknown',
],
customGroups: [],
environment: 'node',
},
],
},
}

Version

This rule was introduced in v0.9.0.

Resources

Table of Contents