🔧 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');
Unbound 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):
groups
pathGroups
pathGroupsExcludedImportTypes
distinctGroup
newlines-between
alphabetize
named
warnOnUnassignedImports
sortTypesAmongThemselves
newlines-between-types
consolidateIslands
Valid 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:
- If the import has no corresponding identifiers (e.g.
import './my/thing.js'
), is otherwise "unassigned," or is an unsupported use ofrequire()
, andwarnOnUnassignedImports
is disabled, it will be ignored entirely since the order of these imports may be important for their side-effects - If the import is part of an arcane TypeScript declaration (e.g.
import log = console.log
), it will be considered object. However, note that external module references (e.g.import x = require('z')
) are treated as normalrequire()
s and import-exports (e.g.export import w = y;
) are ignored entirely - If the import is type-only,
"type"
is ingroups
, andsortTypesAmongThemselves
is disabled, it will be considered type (with additional implications if usingpathGroups
and"type"
is inpathGroupsExcludedImportTypes
) - If the import's specifier matches
import/internal-regex
, it will be considered internal - If the import's specifier is an absolute path, it will be considered unknown
- If the import's specifier has the name of a Node.js core module (using is-core-module), it will be considered builtin
- If the import's specifier matches
import/core-modules
, it will be considered builtin - If the import's specifier is a path relative to the parent directory of its containing file (e.g. starts with
../
), it will be considered parent - If the import's specifier is one of
['.', './', './index', './index.js']
, it will be considered index - If the import's specifier is a path relative to its containing file (e.g. starts with
./
), it will be considered sibling - If the import's specifier is a path pointing to a file outside the current package's root directory (determined using package-up), it will be considered external
- If the import's specifier matches
import/external-module-folders
(defaults to matching anything pointing to files within the current package'snode_modules
directory), it will be considered external - If the import's specifier is a path pointing to a file within the current package's root directory (determined using package-up), it will be considered internal
- If the import's specifier has a name that looks like a scoped package (e.g.
@scoped/package-name
), it will be considered external - If the import's specifier has a name that starts with a word character, it will be considered external
- If this point is reached, the import will be ignored entirely
At 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 sortTypesAmongThemselves
.
Valid values: PathGroup[]
Default: []
Sometimes the predefined groups are not fine-grained
enough, especially when using import aliases. pathGroups
defines one or more
PathGroup
s 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 further pathGroups
matching unless they are removed from pathGroupsExcludedImportTypes
.
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"
}
]
}]
}
Valid 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
, paths
in tsconfig.json
, etc) that end up
grouped as "builtin"
or "external"
imports,
remove them from pathGroupsExcludedImportTypes
to ensure they are ordered
correctly.
{
"import/order": ["error", {
"pathGroups": [
{
"pattern": "@app/**",
"group": "external",
"position": "after"
}
],
"pathGroupsExcludedImportTypes": ["builtin"]
}]
}
Valid values: boolean
Default: true
Caution
Currently, distinctGroup
defaults to true
. However, in a later update, the
default will change to false
.
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"
}
]
}]
}
Valid 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-lines
rule, or a tool like Prettier, can be used.
-
If set to
always-and-inside-groups
, it will act likealways
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 './';
Valid 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 after const z = require('a');
when alphabetize
is 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
: usetrue
to ignore case andfalse
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';
Valid 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 order
Given 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';
Valid 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 --fix
since 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';
Valid values: boolean
Default: false
Note
This setting is only meaningful when "type"
is included in groups
.
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
sortTypesAmongThemselves
to true
:
{
"import/order": ["error", {
"groups": ["type", "builtin", "parent", "sibling", "index"],
"alphabetize": { "order": "asc" },
"sortTypesAmongThemselves": true
}]
}
The same example will pass.
Valid values: "ignore" | "always" | "always-and-inside-groups" | "never"
Default: the value of newlines-between
Note
This setting is only meaningful when sortTypesAmongThemselves
is 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 sortTypesAmongThemselves
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"],
"sortTypesAmongThemselves": 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"],
"sortTypesAmongThemselves": 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: true
will take precedence over newlines-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"],
"sortTypesAmongThemselves": 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"],
"sortTypesAmongThemselves": 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 "./";
Valid values: "inside-groups" | "never"
Default: "never"
Note
This setting is only meaningful when newlines-between
and/or newlines-between-types
is 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:
consolidateIslands
is set to"inside-groups"
newlines-between
is set to"always-and-inside-groups"
newlines-between-types
is set to"never"
sortTypesAmongThemselves
is set totrue
Then newlines-between-types
will yield to consolidateIslands
and allow new lines to separate multi-line imports and a single new line to separate all type-only imports from all normal imports. Other than that, newlines-between-types: "never"
functions as described.
This configuration is useful to keep 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": [],
"sortTypesAmongThemselves": true,
"consolidateIslands": "inside-groups"
}]
}
Important
Pay special attention to the value of pathGroupsExcludedImportTypes
in 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 from pathGroups
matching by default.
The fix is to remove "external"
(and, in this example, the others) from pathGroupsExcludedImportTypes
.
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';