From d5f295081ed1fcf9ff1b21a1a586cc50caebe36f Mon Sep 17 00:00:00 2001 From: "Xunnamius (Romulus)" Date: Mon, 18 Nov 2024 03:06:33 -0800 Subject: [PATCH] [Docs] `extensions`, `order`: improve documentation --- .markdownlint.json | 3 + CHANGELOG.md | 5 + docs/rules/extensions.md | 55 ++- docs/rules/order.md | 915 ++++++++++++++++++++++++++++++++------- 4 files changed, 815 insertions(+), 163 deletions(-) diff --git a/.markdownlint.json b/.markdownlint.json index d179615f4..02a066730 100644 --- a/.markdownlint.json +++ b/.markdownlint.json @@ -1,5 +1,8 @@ { "line-length": false, + "no-duplicate-heading": { + "siblings_only": true + }, "ul-indent": { "start_indent": 1, "start_indented": true diff --git a/CHANGELOG.md b/CHANGELOG.md index ab57069c4..2174fc46b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange ## [Unreleased] +### Changed +- [Docs] `extensions`, `order`: improve documentation ([#3106], thanks [@Xunnamius]) + ## [2.31.0] - 2024-10-03 ### Added @@ -1152,6 +1155,7 @@ for info on changes for earlier releases. [`memo-parser`]: ./memo-parser/README.md +[#3106]: https://github.com/import-js/eslint-plugin-import/pull/3106 [#3073]: https://github.com/import-js/eslint-plugin-import/pull/3073 [#3072]: https://github.com/import-js/eslint-plugin-import/pull/3072 [#3071]: https://github.com/import-js/eslint-plugin-import/pull/3071 @@ -2018,6 +2022,7 @@ for info on changes for earlier releases. [@wtgtybhertgeghgtwtg]: https://github.com/wtgtybhertgeghgtwtg [@xM8WVqaG]: https://github.com/xM8WVqaG [@xpl]: https://github.com/xpl +[@Xunnamius]: https://github.com/Xunnamius [@yesl-kim]: https://github.com/yesl-kim [@yndajas]: https://github.com/yndajas [@yordis]: https://github.com/yordis diff --git a/docs/rules/extensions.md b/docs/rules/extensions.md index 5d15e93f1..bd9f3f358 100644 --- a/docs/rules/extensions.md +++ b/docs/rules/extensions.md @@ -10,13 +10,13 @@ In order to provide a consistent use of file extensions across your code base, t This rule either takes one string option, one object option, or a string and an object option. If it is the string `"never"` (the default value), then the rule forbids the use for any extension. If it is the string `"always"`, then the rule enforces the use of extensions for all import statements. If it is the string `"ignorePackages"`, then the rule enforces the use of extensions for all import statements except package imports. -```json +```jsonc "import/extensions": [, "never" | "always" | "ignorePackages"] ``` By providing an object you can configure each extension separately. -```json +```jsonc "import/extensions": [, { : "never" | "always" | "ignorePackages" }] @@ -26,7 +26,7 @@ By providing an object you can configure each extension separately. By providing both a string and an object, the string will set the default setting for all extensions, and the object can be used to set granular overrides for specific extensions. -```json +```jsonc "import/extensions": [ , "never" | "always" | "ignorePackages", @@ -40,7 +40,7 @@ For example, `["error", "never", { "svg": "always" }]` would require that all ex `ignorePackages` can be set as a separate boolean option like this: -```json +```jsonc "import/extensions": [ , "never" | "always" | "ignorePackages", @@ -58,6 +58,50 @@ Default value of `ignorePackages` is `false`. By default, `import type` and `export type` style imports/exports are ignored. If you want to check them as well, you can set the `checkTypeImports` option to `true`. +Unfortunately, in more advanced linting setups, such as when employing custom specifier aliases (e.g. you're using `eslint-import-resolver-alias`, `paths` in `tsconfig.json`, etc), this rule can be too coarse-grained when determining which imports to ignore and on which to enforce the config. +This is especially troublesome if you have import specifiers that [look like externals or builtins](./order.md#how-imports-are-grouped). + +Set `pathGroupOverrides` to force this rule to always ignore certain imports and never ignore others. +`pathGroupOverrides` accepts an array of one or more [`PathGroupOverride`](#pathgroupoverride) objects. + +For example: + +```jsonc +"import/extensions": [ + , + "never" | "always" | "ignorePackages", + { + ignorePackages: true | false, + pattern: { + : "never" | "always" | "ignorePackages" + }, + pathGroupOverrides: [ + { + pattern: "package-name-to-ignore", + action: "ignore", + }, + { + pattern: "bespoke+alias:{*,*/**}", + action: "enforce", + } + ] + } +] +``` + +> \[!NOTE] +> +> `pathGroupOverrides` is inspired by [`pathGroups` in `'import/order'`](./order.md#pathgroups) and shares a similar interface. +> If you're using `pathGroups` already, you may find `pathGroupOverrides` very useful. + +### `PathGroupOverride` + +| property | required | type | description | +| :--------------: | :------: | :---------------------: | --------------------------------------------------------------- | +| `pattern` | ☑️ | `string` | [Minimatch pattern][16] for specifier matching | +| `patternOptions` | | `object` | [Minimatch options][17]; default: `{nocomment: true}` | +| `action` | ☑️ | `"enforce" \| "ignore"` | What action to take on imports whose specifiers match `pattern` | + ### Exception When disallowing the use of certain extensions this rule makes an exception and allows the use of extension when the file would not be resolvable without extension. @@ -190,3 +234,6 @@ export type { Foo } from './foo'; If you are not concerned about a consistent usage of file extension. In the future, when this rule supports native node ESM resolution, and the plugin is configured to use native rather than transpiled ESM (a config option that is not yet available) - setting this to `always` will have no effect. + +[16]: https://www.npmjs.com/package/minimatch#features +[17]: https://www.npmjs.com/package/minimatch#options diff --git a/docs/rules/order.md b/docs/rules/order.md index 676279953..fcdd4fda7 100644 --- a/docs/rules/order.md +++ b/docs/rules/order.md @@ -6,7 +6,7 @@ Enforce a convention in the order of `require()` / `import` statements. -With the [`groups`](#groups-array) option set to `["builtin", "external", "internal", "parent", "sibling", "index", "object", "type"]` the order is as shown in the following example: +With the [`groups`][18] option set to `["builtin", "external", "internal", "parent", "sibling", "index", "object", "type"]` the order is as shown in the following example: ```ts // 1. node "builtin" modules @@ -32,9 +32,7 @@ import log = console.log; import type { Foo } from 'foo'; ``` -Unassigned imports are ignored, as the order they are imported in may be important. - -Statements using the ES6 `import` syntax must appear before any `require()` statements. +See [here][3] for further details on how imports are grouped. ## Fail @@ -98,86 +96,151 @@ import 'format2.css'; // OK ## Options -This rule supports the following options: +This rule supports the following options (none of which are required): -### `groups: [array]` + - [`groups`][18] + - [`pathGroups`][8] + - [`pathGroupsExcludedImportTypes`][9] + - [`distinctGroup`][32] + - [`newlines-between`][20] + - [`alphabetize`][30] + - [`named`][33] + - [`warnOnUnassignedImports`][5] + - [`sortTypesAmongThemselves`][7] + - [`newlines-between-types`][27] + - [`consolidateIslands`][25] -How groups are defined, and the order to respect. `groups` must be an array of `string` or [`string`]. The only allowed `string`s are: -`"builtin"`, `"external"`, `"internal"`, `"unknown"`, `"parent"`, `"sibling"`, `"index"`, `"object"`, `"type"`. -The enforced order is the same as the order of each element in a group. Omitted types are implicitly grouped together as the last element. Example: +--- -```ts -[ - 'builtin', // Built-in types are first - ['sibling', 'parent'], // Then sibling and parent types. They can be mingled together - 'index', // Then the index file - 'object', - // Then the rest: internal and external type -] -``` +### `groups` -The default value is `["builtin", "external", "parent", "sibling", "index"]`. +Valid values: `("builtin" | "external" | "internal" | "unknown" | "parent" | "sibling" | "index" | "object" | "type")[]` \ +Default: `["builtin", "external", "parent", "sibling", "index"]` -You can set the options like this: +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"`. -```ts -"import/order": [ - "error", - { +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. + +#### Example + +```jsonc +{ + "import/order": ["error", { "groups": [ - "index", - "sibling", - "parent", - "internal", - "external", + // 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", - "type" - ] - } -] + // Then the omitted imports: internal, external, type, unknown + ], + }], +} ``` -### `pathGroups: [array of objects]` +#### How Imports Are Grouped -To be able to group by paths mostly needed with aliases pathGroups can be defined. +An import (a `ImportDeclaration`, `TSImportEqualsDeclaration`, or `require()` `CallExpression`) is grouped by its type (`"require"` vs `"import"`), its [specifier][4], and any corresponding identifiers. -Properties of the objects - -| property | required | type | description | -|----------------|:--------:|--------|---------------| -| pattern | x | string | minimatch pattern for the paths to be in this group (will not be used for builtins or externals) | -| patternOptions | | object | options for minimatch, default: { nocomment: true } | -| group | x | string | one of the allowed groups, the pathGroup will be positioned relative to this group | -| position | | string | defines where around the group the pathGroup will be positioned, can be 'after' or 'before', if not provided pathGroup will be positioned like the group | +```ts +import { identifier1, identifier2 } from 'specifier1'; +import type { MyType } from 'specifier2'; +const identifier3 = require('specifier3'); +``` -```json +Roughly speaking, the grouping algorithm is as follows: + +1. If the import has no corresponding identifiers (e.g. `import './my/thing.js'`), is otherwise "unassigned," or is an unsupported use of `require()`, and [`warnOnUnassignedImports`][5] is disabled, it will be ignored entirely since the order of these imports may be important for their [side-effects][31] +2. 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 normal `require()`s and import-exports (e.g. `export import w = y;`) are ignored entirely +3. If the import is [type-only][6], `"type"` is in `groups`, and [`sortTypesAmongThemselves`][7] is disabled, it will be considered **type** (with additional implications if using [`pathGroups`][8] and `"type"` is in [`pathGroupsExcludedImportTypes`][9]) +4. If the import's specifier matches [`import/internal-regex`][28], it will be considered **internal** +5. If the import's specifier is an absolute path, it will be considered **unknown** +6. If the import's specifier has the name of a Node.js core module (using [is-core-module][10]), it will be considered **builtin** +7. If the import's specifier matches [`import/core-modules`][11], it will be considered **builtin** +8. 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** +9. If the import's specifier is one of `['.', './', './index', './index.js']`, it will be considered **index** +10. If the import's specifier is a path relative to its containing file (e.g. starts with `./`), it will be considered **sibling** +11. If the import's specifier is a path pointing to a file outside the current package's root directory (determined using [package-up][12]), it will be considered **external** +12. If the import's specifier matches [`import/external-module-folders`][29] (defaults to matching anything pointing to files within the current package's `node_modules` directory), it will be considered **external** +13. If the import's specifier is a path pointing to a file within the current package's root directory (determined using [package-up][12]), it will be considered **internal** +14. If the import's specifier has a name that looks like a scoped package (e.g. `@scoped/package-name`), it will be considered **external** +15. If the import's specifier has a name that starts with a word character, it will be considered **external** +16. 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`][7]. + +### `pathGroups` + +Valid values: `PathGroup[]` \ +Default: `[]` + +Sometimes [the predefined groups][18] are not fine-grained +enough, especially when using import aliases. `pathGroups` defines one or more +[`PathGroup`][13]s relative to a predefined group. Imports are associated with a +[`PathGroup`][13] based on path matching against the import specifier (using +[minimatch][14]). + +> \[!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`][9]. + +#### `PathGroup` + +| property | required | type | description | +| :--------------: | :------: | :--------------------: | ------------------------------------------------------------------------------------------------------------------------------- | +| `pattern` | ☑️ | `string` | [Minimatch pattern][16] for specifier matching | +| `patternOptions` | | `object` | [Minimatch options][17]; default: `{nocomment: true}` | +| `group` | ☑️ | [predefined group][18] | One of the [predefined groups][18] 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) | + +#### Example + +```jsonc { "import/order": ["error", { "pathGroups": [ { + // Minimatch pattern used to match against specifiers "pattern": "~/**", - "group": "external" + // The predefined group this PathGroup is defined in relation to + "group": "external", + // How matching imports will be positioned relative to "group" + "position": "after" } ] }] } ``` -### `distinctGroup: [boolean]` +### `pathGroupsExcludedImportTypes` -This changes how `pathGroups[].position` affects grouping. The property is most useful when `newlines-between` is set to `always` and at least 1 `pathGroups` entry has a `position` property set. +Valid values: `("builtin" | "external" | "internal" | "unknown" | "parent" | "sibling" | "index" | "object" | "type")[]` \ +Default: `["builtin", "external", "object"]` -By default, in the context of a particular `pathGroup` entry, when setting `position`, a new "group" will silently be created. That is, even if the `group` is specified, a newline will still separate imports that match that `pattern` with the rest of the group (assuming `newlines-between` is `always`). This is undesirable if your intentions are to use `position` to position _within_ the group (and not create a new one). Override this behavior by setting `distinctGroup` to `false`; this will keep imports within the same group as intended. +By default, imports in certain [groups][18] are excluded +from being matched against [`pathGroups`][8] to prevent overeager sorting. Use +`pathGroupsExcludedImportTypes` to modify which groups are excluded. -Note that currently, `distinctGroup` defaults to `true`. However, in a later update, the default will change to `false` +> \[!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][3] as `"builtin"` or `"external"` imports, +> remove them from `pathGroupsExcludedImportTypes` to ensure they are ordered +> correctly. -Example: +#### Example -```json +```jsonc { "import/order": ["error", { - "newlines-between": "always", "pathGroups": [ { "pattern": "@app/**", @@ -185,54 +248,74 @@ Example: "position": "after" } ], - "distinctGroup": false + "pathGroupsExcludedImportTypes": ["builtin"] }] } ``` -### `pathGroupsExcludedImportTypes: [array]` +### `distinctGroup` + +Valid values: `boolean` \ +Default: `true` + +> \[!CAUTION] +> +> Currently, `distinctGroup` defaults to `true`. However, in a later update, the +> default will change to `false`. -This defines import types that are not handled by configured pathGroups. -If you have added path groups with patterns that look like `"builtin"` or `"external"` imports, you have to remove this group (`"builtin"` and/or `"external"`) from the default exclusion list (e.g., `["builtin", "external", "object"]`, etc) to sort these path groups correctly. +This changes how [`PathGroup.position`][13] affects grouping, and is most useful when [`newlines-between`][20] is set to `always` and at least one [`PathGroup`][13] has a `position` property set. -Example: +When [`newlines-between`][20] is set to `always` and an import matching a specific [`PathGroup.pattern`][13] is encountered, that import is added to a sort of "sub-group" associated with that [`PathGroup`][13]. Thanks to [`newlines-between`][20], imports in this "sub-group" will have a new line separating them from the rest of the imports in [`PathGroup.group`][13]. -```json +This behavior can be undesirable when using [`PathGroup.position`][13] to order imports _within_ [`PathGroup.group`][13] instead of creating a distinct "sub-group". Set `distinctGroup` to `false` to disable the creation of these "sub-groups". + +#### Example + +```jsonc { "import/order": ["error", { + "distinctGroup": false, + "newlines-between": "always", "pathGroups": [ { "pattern": "@app/**", "group": "external", "position": "after" } - ], - "pathGroupsExcludedImportTypes": ["builtin"] + ] }] } ``` -[Import Type](https://github.com/import-js/eslint-plugin-import/blob/HEAD/src/core/importType.js#L90) is resolved as a fixed string in predefined set, it can't be a `patterns`(e.g., `react`, `react-router-dom`, etc). See [#2156] for details. +### `newlines-between` + +Valid values: `"ignore" | "always" | "always-and-inside-groups" | "never"` \ +Default: `"ignore"` + +Enforces or forbids new lines between import groups. -### `newlines-between: [ignore|always|always-and-inside-groups|never]` + - If set to `ignore`, no errors related to new lines between import groups will be reported -Enforces or forbids new lines between import groups: + - If set to `always`, at least one new line between each group will be enforced, and new lines inside a group will be forbidden - - 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. To prevent multiple lines between imports, core `no-multiple-empty-lines` rule can be used. - - If set to `always-and-inside-groups`, it will act like `always` except newlines are allowed inside import groups. - - If set to `never`, no new lines are allowed in the entire import section. + > [!TIP] + > + > To prevent multiple lines between imports, the [`no-multiple-empty-lines` rule][21], or a tool like [Prettier][22], can be used. -The default value is `"ignore"`. + - If set to `always-and-inside-groups`, it will act like `always` except new lines are allowed inside import groups -With the default group setting, the following will be invalid: + - If set to `never`, no new lines are allowed in the entire import section + +#### Example + +With the default [`groups`][18] setting, the following will fail the rule check: ```ts /* eslint import/order: ["error", {"newlines-between": "always"}] */ import fs from 'fs'; import path from 'path'; -import index from './'; import sibling from './foo'; +import index from './'; ``` ```ts @@ -240,8 +323,8 @@ import sibling from './foo'; import fs from 'fs'; import path from 'path'; -import index from './'; import sibling from './foo'; +import index from './'; ``` ```ts @@ -249,21 +332,21 @@ import sibling from './foo'; import fs from 'fs'; import path from 'path'; -import index from './'; - import sibling from './foo'; + +import index from './'; ``` -while those will be valid: +While this will pass: ```ts /* eslint import/order: ["error", {"newlines-between": "always"}] */ import fs from 'fs'; import path from 'path'; -import index from './'; - import sibling from './foo'; + +import index from './'; ``` ```ts @@ -272,163 +355,677 @@ import fs from 'fs'; import path from 'path'; -import index from './'; - import sibling from './foo'; + +import index from './'; ``` ```ts /* eslint import/order: ["error", {"newlines-between": "never"}] */ import fs from 'fs'; import path from 'path'; -import index from './'; import sibling from './foo'; +import index from './'; ``` -### `named: true|false|{ enabled: true|false, import: true|false, export: true|false, require: true|false, cjsExports: true|false, types: mixed|types-first|types-last }` +### `alphabetize` -Enforce ordering of names within imports and exports: +Valid values: `{ order?: "asc" | "desc" | "ignore", orderImportKind?: "asc" | "desc" | "ignore", caseInsensitive?: boolean }` \ +Default: `{ order: "ignore", orderImportKind: "ignore", caseInsensitive: false }` - - If set to `true`, named imports must be ordered according to the `alphabetize` options - - If set to `false`, named imports can occur in any order +Determine the sort order of imports within each [predefined group][18] or [`PathGroup`][8] alphabetically based on specifier. -`enabled` enables the named ordering for all expressions by default. -Use `import`, `export` and `require` and `cjsExports` to override the enablement for the following kind of expressions: +> \[!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][6], 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 + +#### Example + +Given the following settings: + +```jsonc +{ + "import/order": ["error", { + "alphabetize": { + "order": "asc", + "caseInsensitive": true + } + }] +} +``` + +This will fail the rule check: + +```ts +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: + +```ts +import blist from 'BList'; +import * as classnames from 'classnames'; +import aTypes from 'prop-types'; +import React, { PureComponent } from 'react'; +import { compose, apply } from 'xcompose'; +``` + +### `named` + +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`][30]. 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`: - ```ts - import { Readline } from "readline"; - ``` + ```ts + import { Readline } from "readline"; + ``` - `export`: - ```ts - export { Readline }; - // and - export { Readline } from "readline"; - ``` + ```ts + export { Readline }; + // and + export { Readline } from "readline"; + ``` - - `require` + - `require`: - ```ts - const { Readline } = require("readline"); - ``` + ```ts + const { Readline } = require("readline"); + ``` - - `cjsExports` + - `cjsExports`: - ```ts - module.exports.Readline = Readline; - // and - module.exports = { Readline }; - ``` + ```ts + module.exports.Readline = Readline; + // and + module.exports = { Readline }; + ``` -The `types` option allows you to specify the order of `import`s and `export`s of `type` specifiers. -Following values are possible: +Further, the `named.types` option allows you to specify the order of [import identifiers with inline type qualifiers][23] (or "type-only" identifiers/names), e.g. `import { type TypeIdentifier1, normalIdentifier2 } from 'specifier';`. - - `types-first`: forces `type` specifiers to occur first - - `types-last`: forces value specifiers to occur first - - `mixed`: sorts all specifiers in alphabetical order +`named.types` accepts the following values: -The default value is `false`. + - `types-first`: forces type-only identifiers to occur first + - `types-last`: forces type-only identifiers to occur last + - `mixed`: sorts all identifiers in alphabetical order -Example setting: +#### Example -```ts +Given the following settings: + +```jsonc { - named: true, - alphabetize: { - order: 'asc' - } + "import/order": ["error", { + "named": true, + "alphabetize": { + "order": "asc" + } + }] } ``` This will fail the rule check: ```ts -/* eslint import/order: ["error", {"named": true, "alphabetize": {"order": "asc"}}] */ import { compose, apply } from 'xcompose'; ``` While this will pass: ```ts -/* eslint import/order: ["error", {"named": true, "alphabetize": {"order": "asc"}}] */ import { apply, compose } from 'xcompose'; ``` -### `alphabetize: {order: asc|desc|ignore, orderImportKind: asc|desc|ignore, caseInsensitive: true|false}` +### `warnOnUnassignedImports` -Sort the order within each group in alphabetical manner based on **import path**: +Valid values: `boolean` \ +Default: `false` - - `order`: use `asc` to sort in ascending order, and `desc` to sort in descending order (default: `ignore`). - - `orderImportKind`: use `asc` to sort in ascending order various import kinds, e.g. imports prefixed with `type` or `typeof`, with same import path. Use `desc` to sort in descending order (default: `ignore`). - - `caseInsensitive`: use `true` to ignore case, and `false` to consider case (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')`). -Example setting: +> \[!NOTE] +> +> These warnings are not fixable with `--fix` since unassigned imports might be +> used for their +> [side-effects][31], +> and changing the order of such imports cannot be done safely. -```ts -alphabetize: { - order: 'asc', /* sort in ascending order. Options: ['ignore', 'asc', 'desc'] */ - caseInsensitive: true /* ignore case. Options: [true, false] */ +#### Example + +Given the following settings: + +```jsonc +{ + "import/order": ["error", { + "warnOnUnassignedImports": true + }] } ``` This will fail the rule check: ```ts -/* eslint import/order: ["error", {"alphabetize": {"order": "asc", "caseInsensitive": true}}] */ -import React, { PureComponent } from 'react'; -import aTypes from 'prop-types'; -import { compose, apply } from 'xcompose'; -import * as classnames from 'classnames'; -import blist from 'BList'; +import fs from 'fs'; +import './styles.css'; +import path from 'path'; ``` While this will pass: ```ts -/* eslint import/order: ["error", {"alphabetize": {"order": "asc", "caseInsensitive": true}}] */ -import blist from 'BList'; -import * as classnames from 'classnames'; -import aTypes from 'prop-types'; -import React, { PureComponent } from 'react'; -import { compose, apply } from 'xcompose'; +import fs from 'fs'; +import path from 'path'; +import './styles.css'; ``` -### `warnOnUnassignedImports: true|false` +### `sortTypesAmongThemselves` + +Valid values: `boolean` \ +Default: `false` + +> \[!NOTE] +> +> This setting is only meaningful when `"type"` is included in [`groups`][18]. + +Sort [type-only imports][6] separately from normal non-type imports. - - default: `false` +When enabled, the intragroup sort order of [type-only imports][6] will mirror the intergroup ordering of normal imports as defined by [`groups`][18], [`pathGroups`][8], etc. -Warns when unassigned imports are out of order. These warning will not be fixed -with `--fix` because unassigned imports are used for side-effects and changing the -import of order of modules with side effects can not be done automatically in a -way that is safe. +#### Example + +Given the following settings: + +```jsonc +{ + "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: + +```ts +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][6] are considered part of one global +[`"type"` group](#how-imports-are-grouped) by default. However, if we set +`sortTypesAmongThemselves` to `true`: + +```jsonc +{ + "import/order": ["error", { + "groups": ["type", "builtin", "parent", "sibling", "index"], + "alphabetize": { "order": "asc" }, + "sortTypesAmongThemselves": true + }] +} +``` + +The same example will pass. + +### `newlines-between-types` + +Valid values: `"ignore" | "always" | "always-and-inside-groups" | "never"` \ +Default: the value of [`newlines-between`][20] + +> \[!NOTE] +> +> This setting is only meaningful when [`sortTypesAmongThemselves`][7] is enabled. + +`newlines-between-types` is functionally identical to [`newlines-between`][20] except it only enforces or forbids new lines between _[type-only][6] import groups_, which exist only when [`sortTypesAmongThemselves`][7] 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`][20]. + +#### Example + +Given the following settings: + +```jsonc +{ + "import/order": ["error", { + "groups": ["type", "builtin", "parent", "sibling", "index"], + "sortTypesAmongThemselves": true, + "newlines-between": "always" + }] +} +``` This will fail the rule check: ```ts -/* eslint import/order: ["error", {"warnOnUnassignedImports": true}] */ -import fs from 'fs'; -import './styles.css'; -import path from 'path'; +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 this will pass: +However, if we set `newlines-between-types` to `"ignore"`: + +```jsonc +{ + "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`][27] and _not `newlines-between`_. + +> \[!IMPORTANT] +> +> In certain situations, [`consolidateIslands: true`][25] 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`][20] is set to `"never"`: + +```jsonc +{ + "import/order": ["error", { + "groups": ["type", "builtin", "parent", "sibling", "index"], + "sortTypesAmongThemselves": true, + "newlines-between": "never", + "newlines-between-types": "always" + }] +} +``` ```ts -/* eslint import/order: ["error", {"warnOnUnassignedImports": true}] */ -import fs from 'fs'; -import path from 'path'; -import './styles.css'; +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 "./"; ``` -## Related +While the following fails due to the new line between the last type import and the first normal import: + +```jsonc +{ + "import/order": ["error", { + "groups": ["type", "builtin", "parent", "sibling", "index"], + "sortTypesAmongThemselves": true, + "newlines-between": "always", + "newlines-between-types": "never" + }] +} +``` + +```ts +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 "./"; +``` + +### `consolidateIslands` - - [`import/external-module-folders`] setting +Valid values: `"inside-groups" | "never"` \ +Default: `"never"` - - [`import/internal-regex`] setting +> \[!NOTE] +> +> This setting is only meaningful when [`newlines-between`][20] and/or [`newlines-between-types`][27] is set to `"always-and-inside-groups"`. -[`import/external-module-folders`]: ../../README.md#importexternal-module-folders +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][18] or [`pathGroups`][8]. + +> \[!IMPORTANT] +> +> When all of the following are true: +> +> - `consolidateIslands` is set to `"inside-groups"` +> - [`newlines-between`][20] is set to `"always-and-inside-groups"` +> - [`newlines-between-types`][27] is set to `"never"` +> - [`sortTypesAmongThemselves`][7] is set to `true` +> +> Then [`newlines-between-types`][27] will yield to `consolidateIslands` and allow new lines to separate multi-line imports and a single new line to separate all [type-only imports][6] from all normal imports. Other than that, [`newlines-between-types: "never"`][27] 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. + +#### Example + +Given the following settings: + +```jsonc +{ + "import/order": ["error", { + "newlines-between": "always-and-inside-groups", + "consolidateIslands": "inside-groups" + }] +} +``` + +This will fail the rule check: + +```ts +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): + +```ts +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`][20]. + +The same holds true for the next example; when given the following settings: + +```jsonc +{ + "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`][9]** 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](#how-imports-are-grouped), and imports in that group are excluded from [`pathGroups`][8] matching by default. +> +> The fix is to remove `"external"` (and, in this example, the others) from [`pathGroupsExcludedImportTypes`][9]. + +This will fail the rule check: + +```ts +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): + +```ts +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'; +``` + +## Related -[`import/internal-regex`]: ../../README.md#importinternal-regex + - [`import/external-module-folders`][29] + - [`import/internal-regex`][28] + - [`import/core-modules`][11] + +[3]: #how-imports-are-grouped +[4]: https://nodejs.org/api/esm.html#terminology +[5]: #warnonunassignedimports +[6]: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export +[7]: #sorttypesamongthemselves +[8]: #pathgroups +[9]: #pathgroupsexcludedimporttypes +[10]: https://www.npmjs.com/package/is-core-module +[11]: ../../README.md#importcore-modules +[12]: https://www.npmjs.com/package/package-up +[13]: #pathgroup +[14]: https://www.npmjs.com/package/minimatch +[16]: https://www.npmjs.com/package/minimatch#features +[17]: https://www.npmjs.com/package/minimatch#options +[18]: #groups +[20]: #newlines-between +[21]: https://eslint.org/docs/latest/rules/no-multiple-empty-lines +[22]: https://prettier.io +[23]: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html#type-modifiers-on-import-names +[25]: #consolidateislands +[27]: #newlines-between-types +[28]: ../../README.md#importinternal-regex +[29]: ../../README.md#importexternal-module-folders +[30]: #alphabetize +[31]: https://webpack.js.org/guides/tree-shaking#mark-the-file-as-side-effect-free +[32]: #distinctgroup +[33]: #named