🔧 This rule is automatically fixable by the --fix CLI option.
Enforce a convention in the order of require() / import statements.
With the groups option set to ["builtin", "external", "internal", "parent", "sibling", "index", "object", "type"] the order is as shown in the following example:
// 1. node "builtin" modules
import fs from 'fs';
import path from 'path';
// 2. "external" modules
import _ from 'lodash';
import chalk from 'chalk';
// 3. "internal" modules
// (if you have configured your path or webpack to handle your internal paths differently)
import foo from 'src/foo';
// 4. modules from a "parent" directory
import foo from '../foo';
import qux from '../../foo/qux';
// 5. "sibling" modules from the same or a sibling's directory
import bar from './bar';
import baz from './bar/baz';
// 6. "index" of the current directory
import main from './';
// 7. "object"-imports (only available in TypeScript)
import log = console.log;
// 8. "type" imports (only available in Flow and TypeScript)
import type { Foo } from 'foo';
See here for further details on how imports are grouped.
import _ from 'lodash';
import path from 'path'; // `path` import should occur before import of `lodash`
// -----
var _ = require('lodash');
var path = require('path'); // `path` import should occur before import of `lodash`
// -----
var path = require('path');
import foo from './foo'; // `import` statements must be before `require` statement
import path from 'path';
import _ from 'lodash';
// -----
var path = require('path');
var _ = require('lodash');
// -----
// Allowed as ̀`babel-register` is not assigned.
require('babel-register');
var path = require('path');
// -----
// Allowed as `import` must be before `require`
import foo from './foo';
var path = require('path');
--fixUnbound imports are assumed to have side effects, and will never be moved/reordered. This can cause other imports to get "stuck" around them, and the fix to fail.
import b from 'b'
import 'format.css'; // This will prevent --fix from working.
import a from 'a'
As a workaround, move unbound imports to be entirely above or below bound ones.
import 'format1.css'; // OK
import b from 'b'
import a from 'a'
import 'format2.css'; // OK
This rule supports the following options (none of which are required):
groupspathGroupspathGroupsExcludedImportTypesdistinctGroupnewlines-betweenalphabetizenamedwarnOnUnassignedImportssortTypesGroupnewlines-between-typesconsolidateIslandsgroupsValid values: ("builtin" | "external" | "internal" | "unknown" | "parent" | "sibling" | "index" | "object" | "type")[] \
Default: ["builtin", "external", "parent", "sibling", "index"]
Determines which imports are subject to ordering, and how to order
them. The predefined groups are: "builtin", "external", "internal",
"unknown", "parent", "sibling", "index", "object", and "type".
The import order enforced by this rule is the same as the order of each group
in groups. Imports belonging to groups omitted from groups are lumped
together at the end.
{
"import/order": ["error", {
"groups": [
// Imports of builtins are first
"builtin",
// Then sibling and parent imports. They can be mingled together
["sibling", "parent"],
// Then index file imports
"index",
// Then any arcane TypeScript imports
"object",
// Then the omitted imports: internal, external, type, unknown
],
}],
}
An import (a ImportDeclaration, TSImportEqualsDeclaration, or require() CallExpression) is grouped by its type ("require" vs "import"), its specifier, and any corresponding identifiers.
import { identifier1, identifier2 } from 'specifier1';
import type { MyType } from 'specifier2';
const identifier3 = require('specifier3');
Roughly speaking, the grouping algorithm is as follows:
import './my/thing.js'), is otherwise "unassigned," or is an unsupported use of require(), and warnOnUnassignedImports is disabled, it will be ignored entirely since the order of these imports may be important for their side-effectsimport log = console.log), it will be considered object. However, note that external module references (e.g. import x = require('z')) are treated as normal require()s and import-exports (e.g. export import w = y;) are ignored entirely"type" is in groups, and sortTypesGroup is disabled, it will be considered type (with additional implications if using pathGroups and "type" is in pathGroupsExcludedImportTypes)import/internal-regex, it will be considered internalimport/core-modules, it will be considered builtin../), it will be considered parent['.', './', './index', './index.js'], it will be considered index./), it will be considered siblingimport/external-module-folders (defaults to matching anything pointing to files within the current package's node_modules directory), it will be considered external@scoped/package-name), it will be considered externalAt the end of the process, if they co-exist in the same file, all top-level require() statements that haven't been ignored are shifted (with respect to their order) below any ES6 import or similar declarations. Finally, any type-only declarations are potentially reorganized according to sortTypesGroup.
pathGroupsValid values: PathGroup[] \
Default: []
Sometimes the predefined groups are not fine-grained enough, especially when using import aliases.
pathGroups defines one or more PathGroups relative to a predefined group.
Imports are associated with a PathGroup based on path matching against the import specifier (using minimatch).
[!IMPORTANT]
Note that, by default, imports grouped as
"builtin","external", or"object"will not be considered for furtherpathGroupsmatching unless they are removed frompathGroupsExcludedImportTypes.
PathGroup| property | required | type | description |
|---|---|---|---|
pattern |
☑️ | string |
Minimatch pattern for specifier matching |
patternOptions |
object |
Minimatch options; default: {nocomment: true} |
|
group |
☑️ | predefined group | One of the predefined groups to which matching imports will be positioned relatively |
position |
"after" \| "before" |
Where, in relation to group, matching imports will be positioned; default: same position as group (neither before or after) |
{
"import/order": ["error", {
"pathGroups": [
{
// Minimatch pattern used to match against specifiers
"pattern": "~/**",
// The predefined group this PathGroup is defined in relation to
"group": "external",
// How matching imports will be positioned relative to "group"
"position": "after"
}
]
}]
}
pathGroupsExcludedImportTypesValid values: ("builtin" | "external" | "internal" | "unknown" | "parent" | "sibling" | "index" | "object" | "type")[] \
Default: ["builtin", "external", "object"]
By default, imports in certain groups are excluded from being matched against pathGroups to prevent overeager sorting.
Use pathGroupsExcludedImportTypes to modify which groups are excluded.
[!TIP]
If using imports with custom specifier aliases (e.g. you're using
eslint-import-resolver-alias,pathsintsconfig.json, etc) that end up grouped as"builtin"or"external"imports, remove them frompathGroupsExcludedImportTypesto ensure they are ordered correctly.
{
"import/order": ["error", {
"pathGroups": [
{
"pattern": "@app/**",
"group": "external",
"position": "after"
}
],
"pathGroupsExcludedImportTypes": ["builtin"]
}]
}
distinctGroupValid values: boolean \
Default: true
[!CAUTION]
Currently,
distinctGroupdefaults totrue. However, in a later update, the default will change tofalse.
This changes how PathGroup.position affects grouping, and is most useful when newlines-between is set to always and at least one PathGroup has a position property set.
When newlines-between is set to always and an import matching a specific PathGroup.pattern is encountered, that import is added to a sort of "sub-group" associated with that PathGroup. Thanks to newlines-between, imports in this "sub-group" will have a new line separating them from the rest of the imports in PathGroup.group.
This behavior can be undesirable when using PathGroup.position to order imports within PathGroup.group instead of creating a distinct "sub-group". Set distinctGroup to false to disable the creation of these "sub-groups".
{
"import/order": ["error", {
"distinctGroup": false,
"newlines-between": "always",
"pathGroups": [
{
"pattern": "@app/**",
"group": "external",
"position": "after"
}
]
}]
}
newlines-betweenValid values: "ignore" | "always" | "always-and-inside-groups" | "never" \
Default: "ignore"
Enforces or forbids new lines between import groups.
If set to ignore, no errors related to new lines between import groups will be reported
If set to always, at least one new line between each group will be enforced, and new lines inside a group will be forbidden
[!TIP]
To prevent multiple lines between imports, the
no-multiple-empty-linesrule, or a tool like Prettier, can be used.
If set to always-and-inside-groups, it will act like always except new lines are allowed inside import groups
If set to never, no new lines are allowed in the entire import section
With the default groups setting, the following will fail the rule check:
/* eslint import/order: ["error", {"newlines-between": "always"}] */
import fs from 'fs';
import path from 'path';
import sibling from './foo';
import index from './';
/* eslint import/order: ["error", {"newlines-between": "always-and-inside-groups"}] */
import fs from 'fs';
import path from 'path';
import sibling from './foo';
import index from './';
/* eslint import/order: ["error", {"newlines-between": "never"}] */
import fs from 'fs';
import path from 'path';
import sibling from './foo';
import index from './';
While this will pass:
/* eslint import/order: ["error", {"newlines-between": "always"}] */
import fs from 'fs';
import path from 'path';
import sibling from './foo';
import index from './';
/* eslint import/order: ["error", {"newlines-between": "always-and-inside-groups"}] */
import fs from 'fs';
import path from 'path';
import sibling from './foo';
import index from './';
/* eslint import/order: ["error", {"newlines-between": "never"}] */
import fs from 'fs';
import path from 'path';
import sibling from './foo';
import index from './';
alphabetizeValid values: { order?: "asc" | "desc" | "ignore", orderImportKind?: "asc" | "desc" | "ignore", caseInsensitive?: boolean } \
Default: { order: "ignore", orderImportKind: "ignore", caseInsensitive: false }
Determine the sort order of imports within each predefined group or PathGroup alphabetically based on specifier.
[!NOTE]
Imports will be alphabetized based on their specifiers, not by their identifiers. For example,
const a = require('z');will come afterconst z = require('a');whenalphabetizeis set to{ order: "asc" }.
Valid properties and their values include:
order: use "asc" to sort in ascending order, "desc" to sort in descending order, or "ignore" to prevent sorting
orderImportKind: use "asc" to sort various import kinds, e.g. type-only and typeof imports, in ascending order, "desc" to sort them in descending order, or "ignore" to prevent sorting
caseInsensitive: use true to ignore case and false to consider case when sorting
Given the following settings:
{
"import/order": ["error", {
"alphabetize": {
"order": "asc",
"caseInsensitive": true
}
}]
}
This will fail the rule check:
import React, { PureComponent } from 'react';
import aTypes from 'prop-types';
import { compose, apply } from 'xcompose';
import * as classnames from 'classnames';
import blist from 'BList';
While this will pass:
import blist from 'BList';
import * as classnames from 'classnames';
import aTypes from 'prop-types';
import React, { PureComponent } from 'react';
import { compose, apply } from 'xcompose';
namedValid values: boolean | { enabled: boolean, import?: boolean, export?: boolean, require?: boolean, cjsExports?: boolean, types?: "mixed" | "types-first" | "types-last" } \
Default: false
Enforce ordering of names within imports and exports.
If set to true or { enabled: true }, all named imports must be ordered according to alphabetize.
If set to false or { enabled: false }, named imports can occur in any order.
If set to { enabled: true, ... }, and any of the properties import, export, require, or cjsExports are set to false, named ordering is disabled with respect to the following kind of expressions:
import: import { Readline } from "readline";
export: export { Readline };
// and
export { Readline } from "readline";
require: const { Readline } = require("readline");
cjsExports: module.exports.Readline = Readline;
// and
module.exports = { Readline };
Further, the named.types option allows you to specify the order of import identifiers with inline type qualifiers (or "type-only" identifiers/names), e.g. import { type TypeIdentifier1, normalIdentifier2 } from 'specifier';.
named.types accepts the following values:
types-first: forces type-only identifiers to occur firsttypes-last: forces type-only identifiers to occur lastmixed: sorts all identifiers in alphabetical orderGiven the following settings:
{
"import/order": ["error", {
"named": true,
"alphabetize": {
"order": "asc"
}
}]
}
This will fail the rule check:
import { compose, apply } from 'xcompose';
While this will pass:
import { apply, compose } from 'xcompose';
warnOnUnassignedImportsValid values: boolean \
Default: false
Warn when "unassigned" imports are out of order.
Unassigned imports are imports with no corresponding identifiers (e.g. import './my/thing.js' or require('./side-effects.js')).
[!NOTE]
These warnings are not fixable with
--fixsince unassigned imports might be used for their side-effects, and changing the order of such imports cannot be done safely.
Given the following settings:
{
"import/order": ["error", {
"warnOnUnassignedImports": true
}]
}
This will fail the rule check:
import fs from 'fs';
import './styles.css';
import path from 'path';
While this will pass:
import fs from 'fs';
import path from 'path';
import './styles.css';
sortTypesGroupValid values: boolean \
Default: false
[!NOTE]
This setting is only meaningful when
"type"is included ingroups.
Sort type-only imports separately from normal non-type imports.
When enabled, the intragroup sort order of type-only imports will mirror the intergroup ordering of normal imports as defined by groups, pathGroups, etc.
Given the following settings:
{
"import/order": ["error", {
"groups": ["type", "builtin", "parent", "sibling", "index"],
"alphabetize": { "order": "asc" }
}]
}
This will fail the rule check even though it's logically ordered as we expect (builtins come before parents, parents come before siblings, siblings come before indices), the only difference is we separated type-only imports from normal imports:
import type A from "fs";
import type B from "path";
import type C from "../foo.js";
import type D from "./bar.js";
import type E from './';
import a from "fs";
import b from "path";
import c from "../foo.js";
import d from "./bar.js";
import e from "./";
This happens because type-only imports are considered part of one global
"type" group by default. However, if we set
sortTypesGroup to true:
{
"import/order": ["error", {
"groups": ["type", "builtin", "parent", "sibling", "index"],
"alphabetize": { "order": "asc" },
"sortTypesGroup": true
}]
}
The same example will pass.
newlines-between-typesValid values: "ignore" | "always" | "always-and-inside-groups" | "never" \
Default: the value of newlines-between
[!NOTE]
This setting is only meaningful when
sortTypesGroupis enabled.
newlines-between-types is functionally identical to newlines-between except it only enforces or forbids new lines between type-only import groups, which exist only when sortTypesGroup is enabled.
In addition, when determining if a new line is enforceable or forbidden between the type-only imports and the normal imports, newlines-between-types takes precedence over newlines-between.
Given the following settings:
{
"import/order": ["error", {
"groups": ["type", "builtin", "parent", "sibling", "index"],
"sortTypesGroup": true,
"newlines-between": "always"
}]
}
This will fail the rule check:
import type A from "fs";
import type B from "path";
import type C from "../foo.js";
import type D from "./bar.js";
import type E from './';
import a from "fs";
import b from "path";
import c from "../foo.js";
import d from "./bar.js";
import e from "./";
However, if we set newlines-between-types to "ignore":
{
"import/order": ["error", {
"groups": ["type", "builtin", "parent", "sibling", "index"],
"sortTypesGroup": true,
"newlines-between": "always",
"newlines-between-types": "ignore"
}]
}
The same example will pass.
Note the new line after import type E from './'; but before import a from "fs";. This new line separates the type-only imports from the normal imports. Its existence is governed by newlines-between-types and not newlines-between.
[!IMPORTANT]
In certain situations,
consolidateIslands: truewill take precedence overnewlines-between-types: "never", if used, when it comes to the new line separating type-only imports from normal imports.
The next example will pass even though there's a new line preceding the normal import and newlines-between is set to "never":
{
"import/order": ["error", {
"groups": ["type", "builtin", "parent", "sibling", "index"],
"sortTypesGroup": true,
"newlines-between": "never",
"newlines-between-types": "always"
}]
}
import type A from "fs";
import type B from "path";
import type C from "../foo.js";
import type D from "./bar.js";
import type E from './';
import a from "fs";
import b from "path";
import c from "../foo.js";
import d from "./bar.js";
import e from "./";
While the following fails due to the new line between the last type import and the first normal import:
{
"import/order": ["error", {
"groups": ["type", "builtin", "parent", "sibling", "index"],
"sortTypesGroup": true,
"newlines-between": "always",
"newlines-between-types": "never"
}]
}
import type A from "fs";
import type B from "path";
import type C from "../foo.js";
import type D from "./bar.js";
import type E from './';
import a from "fs";
import b from "path";
import c from "../foo.js";
import d from "./bar.js";
import e from "./";
consolidateIslandsValid values: "inside-groups" | "never" \
Default: "never"
[!NOTE]
This setting is only meaningful when
newlines-betweenand/ornewlines-between-typesis set to"always-and-inside-groups".
When set to "inside-groups", this ensures imports spanning multiple lines are separated from other imports with a new line while single-line imports are grouped together (and the space between them consolidated) if they belong to the same group or pathGroups.
[!IMPORTANT]
When all of the following are true:
sortTypesGroupis set totrueconsolidateIslandsis set to"inside-groups"newlines-betweenis set to"always-and-inside-groups"whennewlines-between-typesis set to"never"(or vice-versa)Then
newlines-between/newlines-between-typeswill yield toconsolidateIslandsand allow new lines to separate multi-line imports regardless of the"never"setting.This configuration is useful, for instance, to keep single-line type-only imports stacked tightly together at the bottom of your import block to preserve space while still logically organizing normal imports for quick and pleasant reference.
Given the following settings:
{
"import/order": ["error", {
"newlines-between": "always-and-inside-groups",
"consolidateIslands": "inside-groups"
}]
}
This will fail the rule check:
var fs = require('fs');
var path = require('path');
var { util1, util2, util3 } = require('util');
var async = require('async');
var relParent1 = require('../foo');
var {
relParent21,
relParent22,
relParent23,
relParent24,
} = require('../');
var relParent3 = require('../bar');
var { sibling1,
sibling2, sibling3 } = require('./foo');
var sibling2 = require('./bar');
var sibling3 = require('./foobar');
While this will succeed (and is what --fix would yield):
var fs = require('fs');
var path = require('path');
var { util1, util2, util3 } = require('util');
var async = require('async');
var relParent1 = require('../foo');
var {
relParent21,
relParent22,
relParent23,
relParent24,
} = require('../');
var relParent3 = require('../bar');
var { sibling1,
sibling2, sibling3 } = require('./foo');
var sibling2 = require('./bar');
var sibling3 = require('./foobar');
Note the intragroup "islands" of grouped single-line imports, as well as multi-line imports, are surrounded by new lines. At the same time, note the typical new lines separating different groups are still maintained thanks to newlines-between.
The same holds true for the next example; when given the following settings:
{
"import/order": ["error", {
"alphabetize": { "order": "asc" },
"groups": ["external", "internal", "index", "type"],
"pathGroups": [
{
"pattern": "dirA/**",
"group": "internal",
"position": "after"
},
{
"pattern": "dirB/**",
"group": "internal",
"position": "before"
},
{
"pattern": "dirC/**",
"group": "internal"
}
],
"newlines-between": "always-and-inside-groups",
"newlines-between-types": "never",
"pathGroupsExcludedImportTypes": [],
"sortTypesGroup": true,
"consolidateIslands": "inside-groups"
}]
}
[!IMPORTANT]
Pay special attention to the value of
pathGroupsExcludedImportTypesin this example's settings. Without it, the successful example below would fail. This is because the imports with specifiers starting with "dirA/", "dirB/", and "dirC/" are all considered part of the"external"group, and imports in that group are excluded frompathGroupsmatching by default.The fix is to remove
"external"(and, in this example, the others) frompathGroupsExcludedImportTypes.
This will fail the rule check:
import c from 'Bar';
import d from 'bar';
import {
aa,
bb,
cc,
dd,
ee,
ff,
gg
} from 'baz';
import {
hh,
ii,
jj,
kk,
ll,
mm,
nn
} from 'fizz';
import a from 'foo';
import b from 'dirA/bar';
import index from './';
import type { AA,
BB, CC } from 'abc';
import type { Z } from 'fizz';
import type {
A,
B
} from 'foo';
import type { C2 } from 'dirB/Bar';
import type {
D2,
X2,
Y2
} from 'dirB/bar';
import type { E2 } from 'dirB/baz';
import type { C3 } from 'dirC/Bar';
import type {
D3,
X3,
Y3
} from 'dirC/bar';
import type { E3 } from 'dirC/baz';
import type { F3 } from 'dirC/caz';
import type { C1 } from 'dirA/Bar';
import type {
D1,
X1,
Y1
} from 'dirA/bar';
import type { E1 } from 'dirA/baz';
import type { F } from './index.js';
import type { G } from './aaa.js';
import type { H } from './bbb';
While this will succeed (and is what --fix would yield):
import c from 'Bar';
import d from 'bar';
import {
aa,
bb,
cc,
dd,
ee,
ff,
gg
} from 'baz';
import {
hh,
ii,
jj,
kk,
ll,
mm,
nn
} from 'fizz';
import a from 'foo';
import b from 'dirA/bar';
import index from './';
import type { AA,
BB, CC } from 'abc';
import type { Z } from 'fizz';
import type {
A,
B
} from 'foo';
import type { C2 } from 'dirB/Bar';
import type {
D2,
X2,
Y2
} from 'dirB/bar';
import type { E2 } from 'dirB/baz';
import type { C3 } from 'dirC/Bar';
import type {
D3,
X3,
Y3
} from 'dirC/bar';
import type { E3 } from 'dirC/baz';
import type { F3 } from 'dirC/caz';
import type { C1 } from 'dirA/Bar';
import type {
D1,
X1,
Y1
} from 'dirA/bar';
import type { E1 } from 'dirA/baz';
import type { F } from './index.js';
import type { G } from './aaa.js';
import type { H } from './bbb';