# Eslint Plugin Import > πŸ”§ This rule is automatically fixable by the [`--fix`CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/consistent-type-specifier-style.md # import/consistent-type-specifier-style πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). In both Flow and TypeScript you can mark an import as a type-only import by adding a "kind" marker to the import. Both languages support two positions for marker. **At the top-level** which marks all names in the import as type-only and applies to named, default, and namespace (for TypeScript) specifiers: ```ts import type Foo from 'Foo'; import type {Bar} from 'Bar'; // ts only import type * as Bam from 'Bam'; // flow only import typeof Baz from 'Baz'; ``` **Inline** with to the named import, which marks just the specific name in the import as type-only. An inline specifier is only valid for named specifiers, and not for default or namespace specifiers: ```ts import {type Foo} from 'Foo'; // flow only import {typeof Bar} from 'Bar'; ``` ## Rule Details This rule either enforces or bans the use of inline type-only markers for named imports. This rule includes a fixer that will automatically convert your specifiers to the correct form - however the fixer will not respect your preferences around de-duplicating imports. If this is important to you, consider using the [`import/no-duplicates`] rule. [`import/no-duplicates`]: ./no-duplicates.md ## Options The rule accepts a single string option which may be one of: - `'prefer-inline'` - enforces that named type-only specifiers are only ever written with an inline marker; and never as part of a top-level, type-only import. - `'prefer-top-level'` - enforces that named type-only specifiers only ever written as part of a top-level, type-only import; and never with an inline marker. By default the rule will use the `prefer-inline` option. ## Examples ### `prefer-top-level` ❌ Invalid with `["error", "prefer-top-level"]` ```ts import {type Foo} from 'Foo'; import Foo, {type Bar} from 'Foo'; // flow only import {typeof Foo} from 'Foo'; ``` βœ… Valid with `["error", "prefer-top-level"]` ```ts import type {Foo} from 'Foo'; import type Foo, {Bar} from 'Foo'; // flow only import typeof {Foo} from 'Foo'; ``` ### `prefer-inline` ❌ Invalid with `["error", "prefer-inline"]` ```ts import type {Foo} from 'Foo'; import type Foo, {Bar} from 'Foo'; // flow only import typeof {Foo} from 'Foo'; ``` βœ… Valid with `["error", "prefer-inline"]` ```ts import {type Foo} from 'Foo'; import Foo, {type Bar} from 'Foo'; // flow only import {typeof Foo} from 'Foo'; ``` ## When Not To Use It If you aren't using Flow or TypeScript 4.5+, then this rule does not apply and need not be used. If you don't care about, and don't want to standardize how named specifiers are imported then you should not use this rule. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/default.md # import/default πŸ’Ό This rule is enabled in the following configs: ❗ `errors`, β˜‘οΈ `recommended`. If a default import is requested, this rule will report if there is no default export in the imported module. For [ES7], reports if a default is named and exported but is not found in the referenced module. Note: for packages, the plugin will find exported names from [`jsnext:main`], if present in `package.json`. Redux's npm module includes this key, and thereby is lintable, for example. A module path that is [ignored] or not [unambiguously an ES module] will not be reported when imported. [ignored]: ../README.md#importignore [unambiguously an ES module]: https://github.com/bmeck/UnambiguousJavaScriptGrammar ## Rule Details Given: ```js // ./foo.js export default function () { return 42 } // ./bar.js export function bar() { return null } // ./baz.js module.exports = function () { /* ... */ } // node_modules/some-module/index.js exports.sharedFunction = function shared() { /* ... */ } ``` The following is considered valid: ```js import foo from './foo' // assuming 'node_modules' are ignored (true by default) import someModule from 'some-module' ``` ...and the following cases are reported: ```js import bar from './bar' // no default export found in ./bar import baz from './baz' // no default export found in ./baz ``` ## When Not To Use It If you are using CommonJS and/or modifying the exported namespace of any module at runtime, you will likely see false positives with this rule. This rule currently does not interpret `module.exports = ...` as a `default` export, either, so such a situation will be reported in the importing module. ## Further Reading - Lee Byron's [ES7] export proposal - [`import/ignore`] setting - [`jsnext:main`] (Rollup) [ES7]: https://github.com/leebyron/ecmascript-more-export-from [`import/ignore`]: ../../README.md#importignore [`jsnext:main`]: https://github.com/rollup/rollup/wiki/jsnext:main --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/dynamic-import-chunkname.md # import/dynamic-import-chunkname πŸ’‘ This rule is manually fixable by [editor suggestions](https://eslint.org/docs/latest/use/core-concepts#rule-suggestions). This rule reports any dynamic imports without a webpackChunkName specified in a leading block comment in the proper format. This rule enforces naming of webpack chunks in dynamic imports. When you don't explicitly name chunks, webpack will autogenerate chunk names that are not consistent across builds, which prevents long-term browser caching. ## Rule Details This rule runs against `import()` by default, but can be configured to also run against an alternative dynamic-import function, e.g. 'dynamicImport.' You can also configure the regex format you'd like to accept for the webpackChunkName - for example, if we don't want the number 6 to show up in our chunk names: ```javascript { "import/dynamic-import-chunkname": [2, { importFunctions: ["dynamicImport"], webpackChunknameFormat: "[a-zA-Z0-57-9-/_]+", allowEmpty: false }] } ``` ### invalid The following patterns are invalid: ```javascript // no leading comment import('someModule'); // incorrectly formatted comment import( /*webpackChunkName:"someModule"*/ 'someModule', ); import( /* webpackChunkName : "someModule" */ 'someModule', ); // chunkname contains a 6 (forbidden by rule config) import( /* webpackChunkName: "someModule6" */ 'someModule', ); // invalid syntax for webpack comment import( /* totally not webpackChunkName: "someModule" */ 'someModule', ); // single-line comment, not a block-style comment import( // webpackChunkName: "someModule" 'someModule', ); // chunk names are disallowed when eager mode is set import( /* webpackMode: "eager" */ /* webpackChunkName: "someModule" */ 'someModule', ) ``` ### valid The following patterns are valid: ```javascript import( /* webpackChunkName: "someModule" */ 'someModule', ); import( /* webpackChunkName: "someOtherModule12345789" */ 'someModule', ); import( /* webpackChunkName: "someModule" */ /* webpackPrefetch: true */ 'someModule', ); import( /* webpackChunkName: "someModule", webpackPrefetch: true */ 'someModule', ); // using single quotes instead of double quotes import( /* webpackChunkName: 'someModule' */ 'someModule', ); ``` ### `allowEmpty: true` If you want to allow dynamic imports without a webpackChunkName, you can set `allowEmpty: true` in the rule config. This will allow dynamic imports without a leading comment, or with a leading comment that does not contain a webpackChunkName. Given `{ "allowEmpty": true }`: ### valid The following patterns are valid: ```javascript import('someModule'); import( /* webpackChunkName: "someModule" */ 'someModule', ); ``` ### invalid The following patterns are invalid: ```javascript // incorrectly formatted comment import( /*webpackChunkName:"someModule"*/ 'someModule', ); ``` ## When Not To Use It If you don't care that webpack will autogenerate chunk names and may blow up browser caches and bundle size reports. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/enforce-node-protocol-usage.md # import/enforce-node-protocol-usage πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Enforce either using, or omitting, the `node:` protocol when importing Node.js builtin modules. ## Rule Details This rule enforces that builtins node imports are using, or omitting, the `node:` protocol. Determining whether a specifier is a core module depends on the node version being used to run `eslint`. This version can be specified in the configuration with the [`import/node-version` setting](../../README.md#importnode-version). Reasons to prefer using the protocol include: - the code is more explicitly and clearly referencing a Node.js built-in module Reasons to prefer omitting the protocol include: - some tools don't support the `node:` protocol - the code is more portable, because import maps and automatic polyfilling can be used ## Options The rule requires a single string option which may be one of: - `'always'` - enforces that builtins node imports are using the `node:` protocol. - `'never'` - enforces that builtins node imports are not using the `node:` protocol. ## Examples ### `'always'` ❌ Invalid ```js import fs from 'fs'; export { promises } from 'fs'; // require const fs = require('fs/promises'); ``` βœ… Valid ```js import fs from 'node:fs'; export { promises } from 'node:fs'; import * as test from 'node:test'; // require const fs = require('node:fs/promises'); ``` ### `'never'` ❌ Invalid ```js import fs from 'node:fs'; export { promises } from 'node:fs'; // require const fs = require('node:fs/promises'); ``` βœ… Valid ```js import fs from 'fs'; export { promises } from 'fs'; // require const fs = require('fs/promises'); // This rule will not enforce not using `node:` protocol when the module is only available under the `node:` protocol. import * as test from 'node:test'; ``` ## When Not To Use It If you don't want to consistently enforce using, or omitting, the `node:` protocol when importing Node.js builtin modules. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/export.md # import/export πŸ’Ό This rule is enabled in the following configs: ❗ `errors`, β˜‘οΈ `recommended`. Reports funny business with exports, like repeated exports of names or defaults. ## Rule Details ```js export default class MyClass { /*...*/ } // Multiple default exports. function makeClass() { return new MyClass(...arguments) } export default makeClass // Multiple default exports. ``` or ```js export const foo = function () { /*...*/ } // Multiple exports of name 'foo'. function bar() { /*...*/ } export { bar as foo } // Multiple exports of name 'foo'. ``` In the case of named/default re-export, all `n` re-exports will be reported, as at least `n-1` of them are clearly mistakes, but it is not clear which one (if any) is intended. Could be the result of copy/paste, code duplication with intent to rename, etc. ## Further Reading - Lee Byron's [ES7] export proposal [ES7]: https://github.com/leebyron/ecmascript-more-export-from --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/exports-last.md # import/exports-last This rule enforces that all exports are declared at the bottom of the file. This rule will report any export declarations that comes before any non-export statements. ## This will be reported ```JS const bool = true export default bool const str = 'foo' ``` ```JS export const bool = true const str = 'foo' ``` ## This will not be reported ```JS const arr = ['bar'] export const bool = true export default bool export function func() { console.log('Hello World 🌍') } export const str = 'foo' ``` ## When Not To Use It If you don't mind exports being sprinkled throughout a file, you may not want to enable this rule. ### ES6 exports only The exports-last rule is currently only working on ES6 exports. You may not want to enable this rule if you're using CommonJS exports. If you need CommonJS support feel free to open an issue or create a PR. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/extensions.md # import/extensions Some file resolve algorithms allow you to omit the file extension within the import source path. For example the `node` resolver (which does not yet support ESM/`import`) can resolve `./foo/bar` to the absolute path `/User/someone/foo/bar.js` because the `.js` extension is resolved automatically by default in CJS. Depending on the resolver you can configure more extensions to get resolved automatically. In order to provide a consistent use of file extensions across your code base, this rule can enforce or disallow the use of certain file extensions. ## Rule Details 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. ```jsonc "import/extensions": [, "never" | "always" | "ignorePackages"] ``` By providing an object you can configure each extension separately. ```jsonc "import/extensions": [, { : "never" | "always" | "ignorePackages" }] ``` For example `{ "js": "always", "json": "never"Β }` would always enforce the use of the `.js` extension but never allow the use of the `.json` extension. 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. ```jsonc "import/extensions": [ , "never" | "always" | "ignorePackages", { : "never" | "always" | "ignorePackages" } ] ``` For example, `["error", "never", { "svg": "always" }]` would require that all extensions are omitted, except for "svg". `ignorePackages` can be set as a separate boolean option like this: ```jsonc "import/extensions": [ , "never" | "always" | "ignorePackages", { ignorePackages: true | false, pattern: { : "never" | "always" | "ignorePackages" } } ] ``` In that case, if you still want to specify extensions, you can do so inside the **pattern** property. 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. For example, given the following folder structure: ```pt β”œβ”€β”€ foo β”‚Β Β  β”œβ”€β”€ bar.js β”‚Β Β  β”œβ”€β”€ bar.json ``` and this import statement: ```js import bar from './foo/bar.json'; ``` then the extension can’t be omitted because it would then resolve to `./foo/bar.js`. ### Examples The following patterns are considered problems when configuration set to "never": ```js import foo from './foo.js'; import bar from './bar.json'; import Component from './Component.jsx'; import express from 'express/index.js'; ``` The following patterns are not considered problems when configuration set to "never": ```js import foo from './foo'; import bar from './bar'; import Component from './Component'; import express from 'express/index'; import * as path from 'path'; ``` The following patterns are considered problems when the configuration is set to "never" and the option "checkTypeImports" is set to `true`: ```js import type { Foo } from './foo.ts'; export type { Foo } from './foo.ts'; ``` The following patterns are considered problems when configuration set to "always": ```js import foo from './foo'; import bar from './bar'; import Component from './Component'; import foo from '@/foo'; ``` The following patterns are not considered problems when configuration set to "always": ```js import foo from './foo.js'; import bar from './bar.json'; import Component from './Component.jsx'; import * as path from 'path'; import foo from '@/foo.js'; ``` The following patterns are considered problems when configuration set to "ignorePackages": ```js import foo from './foo'; import bar from './bar'; import Component from './Component'; ``` The following patterns are not considered problems when configuration set to "ignorePackages": ```js import foo from './foo.js'; import bar from './bar.json'; import Component from './Component.jsx'; import express from 'express'; import foo from '@/foo' ``` The following patterns are not considered problems when configuration set to `['error', 'always', {ignorePackages: true} ]`: ```js import Component from './Component.jsx'; import baz from 'foo/baz.js'; import express from 'express'; import foo from '@/foo'; ``` The following patterns are considered problems when the configuration is set to "always" and the option "checkTypeImports" is set to `true`: ```js import type { Foo } from './foo'; export type { Foo } from './foo'; ``` ## When Not To Use It 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 --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/first.md # import/first πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). This rule reports any imports that come after non-import statements. ## Rule Details ```js import foo from './foo' // some module-level initializer initWith(foo) import bar from './bar' // <- reported ``` Providing `absolute-first` as an option will report any absolute imports (i.e. packages) that come after any relative imports: ```js import foo from 'foo' import bar from './bar' import * as _ from 'lodash' // <- reported ``` If you really want import type ordering, check out [`import/order`]. Notably, `import`s are hoisted, which means the imported modules will be evaluated before any of the statements interspersed between them. Keeping all `import`s together at the top of the file may prevent surprises resulting from this part of the spec. ### On directives Directives are allowed as long as they occur strictly before any `import` declarations, as follows: ```js 'use super-mega-strict' import { suchFoo } from 'lame-fake-module-name' // no report here ``` A directive in this case is assumed to be a single statement that contains only a literal string-valued expression. `'use strict'` would be a good example, except that [modules are always in strict mode](https://262.ecma-international.org/6.0/#sec-strict-mode-code) so it would be surprising to see a `'use strict'` sharing a file with `import`s and `export`s. Given that, see [#255] for the reasoning. ### With Fixer This rule contains a fixer to reorder in-body import to top, the following criteria applied: 1. Never re-order relative to each other, even if `absolute-first` is set. 2. If an import creates an identifier, and that identifier is referenced at module level *before* the import itself, that won't be re-ordered. ## When Not To Use It If you don't mind imports being sprinkled throughout, you may not want to enable this rule. ## Further Reading - [`import/order`]: a major step up from `absolute-first` - Issue [#255] [`import/order`]: ./order.md [#255]: https://github.com/import-js/eslint-plugin-import/issues/255 --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/group-exports.md # import/group-exports Reports when named exports are not grouped together in a single `export` declaration or when multiple assignments to CommonJS `module.exports` or `exports` object are present in a single file. **Rationale:** An `export` declaration or `module.exports` assignment can appear anywhere in the code. By requiring a single export declaration all your exports will remain at one place, making it easier to see what exports a module provides. ## Rule Details This rule warns whenever a single file contains multiple named export declarations or multiple assignments to `module.exports` (or `exports`). ### Valid ```js // A single named export declaration -> ok export const valid = true ``` ```js const first = true const second = true // A single named export declaration -> ok export { first, second, } ``` ```js // Aggregating exports -> ok export { default as module1 } from 'module-1' export { default as module2 } from 'module-2' ``` ```js // A single exports assignment -> ok module.exports = { first: true, second: true } ``` ```js const first = true const second = true // A single exports assignment -> ok module.exports = { first, second, } ``` ```js function test() {} test.property = true test.another = true // A single exports assignment -> ok module.exports = test ``` ```ts const first = true; type firstType = boolean // A single named export declaration (type exports handled separately) -> ok export {first} export type {firstType} ``` ### Invalid ```js // Multiple named export statements -> not ok! export const first = true export const second = true ``` ```js // Aggregating exports from the same module -> not ok! export { module1 } from 'module-1' export { module2 } from 'module-1' ``` ```js // Multiple exports assignments -> not ok! exports.first = true exports.second = true ``` ```js // Multiple exports assignments -> not ok! module.exports = {} module.exports.first = true ``` ```js // Multiple exports assignments -> not ok! module.exports = () => {} module.exports.first = true module.exports.second = true ``` ```ts type firstType = boolean type secondType = any // Multiple named type export statements -> not ok! export type {firstType} export type {secondType} ``` ## When Not To Use It If you do not mind having your exports spread across the file, you can safely turn this rule off. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/imports-first.md # import/imports-first ❌ This rule is deprecated. πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). This rule was **deprecated** in eslint-plugin-import v2.0.0. Please use the corresponding rule [`first`](https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/first.md). --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/max-dependencies.md # import/max-dependencies Forbid modules to have too many dependencies (`import` or `require` statements). This is a useful rule because a module with too many dependencies is a code smell, and usually indicates the module is doing too much and/or should be broken up into smaller modules. Importing multiple named exports from a single module will only count once (e.g. `import {x, y, z} from './foo'` will only count as a single dependency). ## Options This rule has the following options, with these defaults: ```js "import/max-dependencies": ["error", { "max": 10, "ignoreTypeImports": false, }] ``` ### `max` This option sets the maximum number of dependencies allowed. Anything over will trigger the rule. **Default is 10** if the rule is enabled and no `max` is specified. Given a max value of `{"max": 2}`: ### Fail ```js import a from './a'; // 1 const b = require('./b'); // 2 import c from './c'; // 3 - exceeds max! ``` ### Pass ```js import a from './a'; // 1 const anotherA = require('./a'); // still 1 import {x, y, z} from './foo'; // 2 ``` ### `ignoreTypeImports` Ignores `type` imports. Type imports are a feature released in TypeScript 3.8, you can [read more here](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export). Defaults to `false`. Given `{"max": 2, "ignoreTypeImports": true}`: ### Fail ```ts import a from './a'; import b from './b'; import c from './c'; ``` ### Pass ```ts import a from './a'; import b from './b'; import type c from './c'; // Doesn't count against max ``` ## When Not To Use It If you don't care how many dependencies a module has. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/named.md # import/named πŸ’ΌπŸš« This rule is enabled in the following configs: ❗ `errors`, β˜‘οΈ `recommended`. This rule is _disabled_ in the ⌨️ `typescript` config. Verifies that all named imports are part of the set of named exports in the referenced module. For `export`, verifies that all named exports exist in the referenced module. Note: for packages, the plugin will find exported names from [`jsnext:main`] (deprecated) or `module`, if present in `package.json`. Redux's npm module includes this key, and thereby is lintable, for example. A module path that is [ignored] or not [unambiguously an ES module] will not be reported when imported. Note that type imports and exports, as used by [Flow], are always ignored. [ignored]: ../../README.md#importignore [unambiguously an ES module]: https://github.com/bmeck/UnambiguousJavaScriptGrammar [Flow]: https://flow.org/ ## Rule Details Given: ```js // ./foo.js export const foo = "I'm so foo" ``` The following is considered valid: ```js // ./bar.js import { foo } from './foo' // ES7 proposal export { foo as bar } from './foo' // node_modules without jsnext:main are not analyzed by default // (import/ignore setting) import { SomeNonsenseThatDoesntExist } from 'react' ``` ...and the following are reported: ```js // ./baz.js import { notFoo } from './foo' // ES7 proposal export { notFoo as defNotBar } from './foo' // will follow 'jsnext:main', if available import { dontCreateStore } from 'redux' ``` ### Settings [`import/ignore`] can be provided as a setting to ignore certain modules (node_modules, CoffeeScript, CSS if using Webpack, etc.). Given: ```yaml # .eslintrc (YAML) --- settings: import/ignore: - node_modules # included by default, but replaced if explicitly configured - *.coffee$ # can't parse CoffeeScript (unless a custom polyglot parser was configured) ``` and ```coffeescript # ./whatever.coffee exports.whatever = (foo) -> console.log foo ``` then the following is not reported: ```js // ./foo.js // can't be analyzed, and ignored, so not reported import { notWhatever } from './whatever' ``` ## When Not To Use It If you are using CommonJS and/or modifying the exported namespace of any module at runtime, you will likely see false positives with this rule. ## Further Reading - [`import/ignore`] setting - [`jsnext:main`] deprecation - [`pkg.module`] (Rollup) [`jsnext:main`]: https://github.com/jsforum/jsforum/issues/5 [`pkg.module`]: https://github.com/rollup/rollup/wiki/pkg.module [`import/ignore`]: ../../README.md#importignore --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/namespace.md # import/namespace πŸ’Ό This rule is enabled in the following configs: ❗ `errors`, β˜‘οΈ `recommended`. Enforces names exist at the time they are dereferenced, when imported as a full namespace (i.e. `import * as foo from './foo'; foo.bar();` will report if `bar` is not exported by `./foo`.). Will report at the import declaration if there are _no_ exported names found. Also, will report for computed references (i.e. `foo["bar"]()`). Reports on assignment to a member of an imported namespace. Note: for packages, the plugin will find exported names from [`jsnext:main`], if present in `package.json`. Redux's npm module includes this key, and thereby is lintable, for example. A module path that is [ignored] or not [unambiguously an ES module] will not be reported when imported. [ignored]: ../README.md#importignore [unambiguously an ES module]: https://github.com/bmeck/UnambiguousJavaScriptGrammar ## Rule Details Currently, this rule does not check for possible redefinition of the namespace in an intermediate scope. Adherence to the ESLint `no-shadow` rule for namespaces will prevent this from being a problem. For [ES7], reports if an exported namespace would be empty (no names exported from the referenced module.) Given: ```js // @module ./named-exports export const a = 1 const b = 2 export { b } const c = 3 export { c as d } export class ExportedClass { } // ES7 export * as deep from './deep' ``` and: ```js // @module ./deep export const e = "MC2" ``` See what is valid and reported: ```js // @module ./foo import * as names from './named-exports' function great() { return names.a + names.b // so great https://youtu.be/ei7mb8UxEl8 } function notGreat() { doSomethingWith(names.c) // Reported: 'c' not found in imported namespace 'names'. const { a, b, c } = names // also reported, only for 'c' } // also tunnels through re-exported namespaces! function deepTrouble() { doSomethingWith(names.deep.e) // fine doSomethingWith(names.deep.f) // Reported: 'f' not found in deeply imported namespace 'names.deep'. } ``` ### Options #### `allowComputed` Defaults to `false`. When false, will report the following: ```js /*eslint import/namespace: [2, { allowComputed: false }]*/ import * as a from './a' function f(x) { return a[x] // Unable to validate computed reference to imported namespace 'a'. } ``` When set to `true`, the above computed namespace member reference is allowed, but still can't be statically analyzed any further. ## Further Reading - Lee Byron's [ES7] export proposal - [`import/ignore`] setting - [`jsnext:main`](Rollup) [ES7]: https://github.com/leebyron/ecmascript-more-export-from [`import/ignore`]: ../../README.md#importignore [`jsnext:main`]: https://github.com/rollup/rollup/wiki/jsnext:main --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/newline-after-import.md # import/newline-after-import πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Enforces having one or more empty lines after the last top-level import statement or require call. ## Rule Details This rule supports the following options: - `count` which sets the number of newlines that are enforced after the last top-level import statement or require call. This option defaults to `1`. - `exactCount` which enforce the exact numbers of newlines that is mentioned in `count`. This option defaults to `false`. - `considerComments` which enforces the rule on comments after the last import-statement as well when set to true. This option defaults to `false`. Valid: ```js import defaultExport from './foo'; const FOO = 'BAR'; ``` ```js import defaultExport from './foo'; import { bar } from 'bar-lib'; const FOO = 'BAR'; ``` ```js const FOO = require('./foo'); const BAR = require('./bar'); const BAZ = 1; ``` Invalid: ```js import * as foo from 'foo' const FOO = 'BAR'; ``` ```js import * as foo from 'foo'; const FOO = 'BAR'; import { bar } from 'bar-lib'; ``` ```js const FOO = require('./foo'); const BAZ = 1; const BAR = require('./bar'); ``` With `count` set to `2` this will be considered valid: ```js import defaultExport from './foo'; const FOO = 'BAR'; ``` ```js import defaultExport from './foo'; const FOO = 'BAR'; ``` With `count` set to `2` these will be considered invalid: ```js import defaultExport from './foo'; const FOO = 'BAR'; ``` ```js import defaultExport from './foo'; const FOO = 'BAR'; ``` With `count` set to `2` and `exactCount` set to `true` this will be considered valid: ```js import defaultExport from './foo'; const FOO = 'BAR'; ``` With `count` set to `2` and `exactCount` set to `true` these will be considered invalid: ```js import defaultExport from './foo'; const FOO = 'BAR'; ``` ```js import defaultExport from './foo'; const FOO = 'BAR'; ``` ```js import defaultExport from './foo'; const FOO = 'BAR'; ``` ```js import defaultExport from './foo'; const FOO = 'BAR'; ``` With `considerComments` set to `false` this will be considered valid: ```js import defaultExport from './foo' // some comment here. const FOO = 'BAR' ``` With `considerComments` set to `true` this will be considered valid: ```js import defaultExport from './foo' // some comment here. const FOO = 'BAR' ``` With `considerComments` set to `true` this will be considered invalid: ```js import defaultExport from './foo' // some comment here. const FOO = 'BAR' ``` ## Example options usage ```json { "rules": { "import/newline-after-import": ["error", { "count": 2 }] } } ``` ## When Not To Use It If you like to visually group module imports with its usage, you don't want to use this rule. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-absolute-path.md # import/no-absolute-path πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Node.js allows the import of modules using an absolute path such as `/home/xyz/file.js`. That is a bad practice as it ties the code using it to your computer, and therefore makes it unusable in packages distributed on `npm` for instance. This rule forbids the import of modules using absolute paths. ## Rule Details ### Fail ```js import f from '/foo'; import f from '/some/path'; var f = require('/foo'); var f = require('/some/path'); ``` ### Pass ```js import _ from 'lodash'; import foo from 'foo'; import foo from './foo'; var _ = require('lodash'); var foo = require('foo'); var foo = require('./foo'); ``` ### Options By default, only ES6 imports and CommonJS `require` calls will have this rule enforced. You may provide an options object providing true/false for any of - `esmodule`: defaults to `true` - `commonjs`: defaults to `true` - `amd`: defaults to `false` If `{ amd: true }` is provided, dependency paths for AMD-style `define` and `require` calls will be resolved: ```js /*eslint import/no-absolute-path: [2, { commonjs: false, amd: true }]*/ define(['/foo'], function (foo) { /*...*/ }) // reported require(['/foo'], function (foo) { /*...*/ }) // reported const foo = require('/foo') // ignored because of explicit `commonjs: false` ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-amd.md # import/no-amd Reports `require([array], ...)` and `define([array], ...)` function calls at the module scope. Will not report if !=2 arguments, or first argument is not a literal array. Intended for temporary use when migrating to pure ES6 modules. ## Rule Details This will be reported: ```js define(["a", "b"], function (a, b) { /* ... */ }) require(["b", "c"], function (b, c) { /* ... */ }) ``` CommonJS `require` is still valid. ## When Not To Use It If you don't mind mixing module systems (sometimes this is useful), you probably don't want this rule. It is also fairly noisy if you have a larger codebase that is being transitioned from AMD to ES6 modules. ## Contributors Special thanks to @xjamundx for donating his no-define rule as a start to this. ## Further Reading - [`no-commonjs`](./no-commonjs.md): report CommonJS `require` and `exports` - Source: --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-anonymous-default-export.md # import/no-anonymous-default-export Reports if a module's default export is unnamed. This includes several types of unnamed data types; literals, object expressions, arrays, anonymous functions, arrow functions, and anonymous class declarations. Ensuring that default exports are named helps improve the grepability of the codebase by encouraging the re-use of the same identifier for the module's default export at its declaration site and at its import sites. ## Options By default, all types of anonymous default exports are forbidden, but any types can be selectively allowed by toggling them on in the options. The complete default configuration looks like this. ```js "import/no-anonymous-default-export": ["error", { "allowArray": false, "allowArrowFunction": false, "allowAnonymousClass": false, "allowAnonymousFunction": false, "allowCallExpression": true, // The true value here is for backward compatibility "allowNew": false, "allowLiteral": false, "allowObject": false }] ``` ## Rule Details ### Fail ```js export default [] export default () => {} export default class {} export default function () {} /* eslint import/no-anonymous-default-export: [2, {"allowCallExpression": false}] */ export default foo(bar) export default 123 export default {} export default new Foo() ``` ### Pass ```js const foo = 123 export default foo export default class MyClass() {} export default function foo() {} /* eslint import/no-anonymous-default-export: [2, {"allowArray": true}] */ export default [] /* eslint import/no-anonymous-default-export: [2, {"allowArrowFunction": true}] */ export default () => {} /* eslint import/no-anonymous-default-export: [2, {"allowAnonymousClass": true}] */ export default class {} /* eslint import/no-anonymous-default-export: [2, {"allowAnonymousFunction": true}] */ export default function () {} export default foo(bar) /* eslint import/no-anonymous-default-export: [2, {"allowLiteral": true}] */ export default 123 /* eslint import/no-anonymous-default-export: [2, {"allowObject": true}] */ export default {} /* eslint import/no-anonymous-default-export: [2, {"allowNew": true}] */ export default new Foo() ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-commonjs.md # import/no-commonjs Reports `require([string])` function calls. Will not report if >1 argument, or single argument is not a literal string. Reports `module.exports` or `exports.*`, also. Intended for temporary use when migrating to pure ES6 modules. ## Rule Details This will be reported: ```js var mod = require('./mod') , common = require('./common') , fs = require('fs') , whateverModule = require('./not-found') module.exports = { a: "b" } exports.c = "d" ``` ### Allow require If `allowRequire` option is set to `true`, `require` calls are valid: ```js /*eslint no-commonjs: [2, { allowRequire: true }]*/ var mod = require('./mod'); ``` but `module.exports` is reported as usual. ### Allow conditional require By default, conditional requires are allowed: ```js var a = b && require("c") if (typeof window !== "undefined") { require('that-ugly-thing'); } var fs = null; try { fs = require("fs") } catch (error) {} ``` If the `allowConditionalRequire` option is set to `false`, they will be reported. If you don't rely on synchronous module loading, check out [dynamic import](https://github.com/airbnb/babel-plugin-dynamic-import-node). ### Allow primitive modules If `allowPrimitiveModules` option is set to `true`, the following is valid: ```js /*eslint no-commonjs: [2, { allowPrimitiveModules: true }]*/ module.exports = "foo" module.exports = function rule(context) { return { /* ... */ } } ``` but this is still reported: ```js /*eslint no-commonjs: [2, { allowPrimitiveModules: true }]*/ module.exports = { x: "y" } exports.z = function boop() { /* ... */ } ``` This is useful for things like ESLint rule modules, which must export a function as the module. ## When Not To Use It If you don't mind mixing module systems (sometimes this is useful), you probably don't want this rule. It is also fairly noisy if you have a larger codebase that is being transitioned from CommonJS to ES6 modules. ## Contributors Special thanks to @xjamundx for donating the module.exports and exports.* bits. ## Further Reading - [`no-amd`](./no-amd.md): report on AMD `require`, `define` - Source: --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-cycle.md # import/no-cycle Ensures that there is no resolvable path back to this module via its dependencies. This includes cycles of depth 1 (imported module imports me) to `"∞"` (or `Infinity`), if the [`maxDepth`](#maxdepth) option is not set. ```js // dep-b.js import './dep-a.js' export function b() { /* ... */ } ``` ```js // dep-a.js import { b } from './dep-b.js' // reported: Dependency cycle detected. ``` This rule does _not_ detect imports that resolve directly to the linted module; for that, see [`no-self-import`]. This rule ignores type-only imports in Flow and TypeScript syntax (`import type` and `import typeof`), which have no runtime effect. ## Rule Details ### Options By default, this rule only detects cycles for ES6 imports, but see the [`no-unresolved` options](./no-unresolved.md#options) as this rule also supports the same `commonjs` and `amd` flags. However, these flags only impact which import types are _linted_; the import/export infrastructure only registers `import` statements in dependencies, so cycles created by `require` within imported modules may not be detected. #### `maxDepth` There is a `maxDepth` option available to prevent full expansion of very deep dependency trees: ```js /*eslint import/no-cycle: [2, { maxDepth: 1 }]*/ // dep-c.js import './dep-a.js' ``` ```js // dep-b.js import './dep-c.js' export function b() { /* ... */ } ``` ```js // dep-a.js import { b } from './dep-b.js' // not reported as the cycle is at depth 2 ``` This is not necessarily recommended, but available as a cost/benefit tradeoff mechanism for reducing total project lint time, if needed. #### `ignoreExternal` An `ignoreExternal` option is available to prevent the cycle detection to expand to external modules: ```js /*eslint import/no-cycle: [2, { ignoreExternal: true }]*/ // dep-a.js import 'module-b/dep-b.js' export function a() { /* ... */ } ``` ```js // node_modules/module-b/dep-b.js import { a } from './dep-a.js' // not reported as this module is external ``` Its value is `false` by default, but can be set to `true` for reducing total project lint time, if needed. #### `allowUnsafeDynamicCyclicDependency` This option disable reporting of errors if a cycle is detected with at least one dynamic import. ```js // bar.js import { foo } from './foo'; export const bar = foo; // foo.js export const foo = 'Foo'; export function getBar() { return import('./bar'); } ``` > Cyclic dependency are **always** a dangerous anti-pattern as discussed extensively in [#2265](https://github.com/import-js/eslint-plugin-import/issues/2265). Please be extra careful about using this option. #### `disableScc` This option disables a pre-processing step that calculates [Strongly Connected Components](https://en.wikipedia.org/wiki/Strongly_connected_component), which are used for avoiding unnecessary work checking files in different SCCs for cycles. However, under some configurations, this pre-processing may be more expensive than the time it saves. When this option is `true`, we don't calculate any SCC graph, and check all files for cycles (leading to higher time-complexity). Default is `false`. ## When Not To Use It This rule is comparatively computationally expensive. If you are pressed for lint time, or don't think you have an issue with dependency cycles, you may not want this rule enabled. ## Further Reading - [Original inspiring issue](https://github.com/import-js/eslint-plugin-import/issues/941) - Rule to detect that module imports itself: [`no-self-import`] - [`import/external-module-folders`] setting [`no-self-import`]: ./no-self-import.md [`import/external-module-folders`]: ../../README.md#importexternal-module-folders --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-default-export.md # import/no-default-export Prohibit default exports. Mostly an inverse of [`prefer-default-export`]. [`prefer-default-export`]: ./prefer-default-export.md ## Rule Details The following patterns are considered warnings: ```javascript // bad1.js // There is a default export. export const foo = 'foo'; const bar = 'bar'; export default 'bar'; ``` ```javascript // bad2.js // There is a default export. const foo = 'foo'; export { foo as default } ``` The following patterns are not warnings: ```javascript // good1.js // There is only a single module export and it's a named export. export const foo = 'foo'; ``` ```javascript // good2.js // There is more than one named export in the module. export const foo = 'foo'; export const bar = 'bar'; ``` ```javascript // good3.js // There is more than one named export in the module const foo = 'foo'; const bar = 'bar'; export { foo, bar } ``` ```javascript // export-star.js // Any batch export will disable this rule. The remote module is not inspected. export * from './other-module' ``` ## When Not To Use It If you don't care if default imports are used, or if you prefer default imports over named imports. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-deprecated.md # import/no-deprecated Reports use of a deprecated name, as indicated by a JSDoc block with a `@deprecated` tag or TomDoc `Deprecated:` comment. using a JSDoc `@deprecated` tag: ```js // @file: ./answer.js /** * this is what you get when you trust a mouse talk show * @deprecated need to restart the experiment * @returns {Number} nonsense */ export function multiply(six, nine) { return 42 } ``` will report as such: ```js import { multiply } from './answer' // Deprecated: need to restart the experiment function whatever(y, z) { return multiply(y, z) // Deprecated: need to restart the experiment } ``` or using the TomDoc equivalent: ```js // Deprecated: This is what you get when you trust a mouse talk show, need to // restart the experiment. // // Returns a Number nonsense export function multiply(six, nine) { return 42 } ``` Only JSDoc is enabled by default. Other documentation styles can be enabled with the `import/docstyle` setting. ```yaml # .eslintrc.yml settings: import/docstyle: ['jsdoc', 'tomdoc'] ``` ## Worklist - [x] report explicit imports on the import node - [x] support namespaces - [x] should bubble up through deep namespaces (#157) - [x] report explicit imports at reference time (at the identifier) similar to namespace - [x] mark module deprecated if file JSDoc has a @deprecated tag? - [ ] don't flag redeclaration of imported, deprecated names - [ ] flag destructuring --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-duplicates.md # import/no-duplicates ⚠️ This rule _warns_ in the following configs: β˜‘οΈ `recommended`, 🚸 `warnings`. πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Reports if a resolved path is imported more than once. ESLint core has a similar rule ([`no-duplicate-imports`](https://eslint.org/docs/rules/no-duplicate-imports)), but this version is different in two key ways: 1. the paths in the source code don't have to exactly match, they just have to point to the same module on the filesystem. (i.e. `./foo` and `./foo.js`) 2. this version distinguishes Flow `type` imports from standard imports. ([#334](https://github.com/import-js/eslint-plugin-import/pull/334)) ## Rule Details Valid: ```js import SomeDefaultClass, * as names from './mod' // Flow `type` import from same module is fine import type SomeType from './mod' ``` ...whereas here, both `./mod` imports will be reported: ```js import SomeDefaultClass from './mod' // oops, some other import separated these lines import foo from './some-other-mod' import * as names from './mod' // will catch this too, assuming it is the same target module import { something } from './mod.js' ``` The motivation is that this is likely a result of two developers importing different names from the same module at different times (and potentially largely different locations in the file.) This rule brings both (or n-many) to attention. ### Query Strings By default, this rule ignores query strings (i.e. paths followed by a question mark), and thus imports from `./mod?a` and `./mod?b` will be considered as duplicates. However you can use the option `considerQueryString` to handle them as different (primarily because browsers will resolve those imports differently). Config: ```json "import/no-duplicates": ["error", {"considerQueryString": true}] ``` And then the following code becomes valid: ```js import minifiedMod from './mod?minify' import noCommentsMod from './mod?comments=0' import originalMod from './mod' ``` It will still catch duplicates when using the same module and the exact same query string: ```js import SomeDefaultClass from './mod?minify' // This is invalid, assuming `./mod` and `./mod.js` are the same target: import * from './mod.js?minify' ``` ### Inline Type imports TypeScript 4.5 introduced a new [feature](https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/#type-on-import-names) that allows mixing of named value and type imports. In order to support fixing to an inline type import when duplicate imports are detected, `prefer-inline` can be set to true. Config: ```json "import/no-duplicates": ["error", {"prefer-inline": true}] ``` ❌ Invalid `["error", {"prefer-inline": true}]` ```js import { AValue, type AType } from './mama-mia' import type { BType } from './mama-mia' import { CValue } from './papa-mia' import type { CType } from './papa-mia' ``` βœ… Valid with `["error", {"prefer-inline": true}]` ```js import { AValue, type AType, type BType } from './mama-mia' import { CValue, type CType } from './papa-mia' ``` ## When Not To Use It If the core ESLint version is good enough (i.e. you're _not_ using Flow and you _are_ using [`import/extensions`](./extensions.md)), keep it and don't use this. If you like to split up imports across lines or may need to import a default and a namespace, you may not want to enable this rule. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-dynamic-require.md # import/no-dynamic-require The `require` method from CommonJS is used to import modules from different files. Unlike the ES6 `import` syntax, it can be given expressions that will be resolved at runtime. While this is sometimes necessary and useful, in most cases it isn't. Using expressions (for instance, concatenating a path and variable) as the argument makes it harder for tools to do static code analysis, or to find where in the codebase a module is used. This rule forbids every call to `require()` that uses expressions for the module name argument. ## Rule Details ### Fail ```js require(name); require('../' + name); require(`../${name}`); require(name()); ``` ### Pass ```js require('../name'); require(`../name`); ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-empty-named-blocks.md # import/no-empty-named-blocks πŸ”§πŸ’‘ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix) and manually fixable by [editor suggestions](https://eslint.org/docs/latest/use/core-concepts#rule-suggestions). Reports the use of empty named import blocks. ## Rule Details ### Valid ```js import { mod } from 'mod' import Default, { mod } from 'mod' ``` When using typescript ```js import type { mod } from 'mod' ``` When using flow ```js import typeof { mod } from 'mod' ``` ### Invalid ```js import {} from 'mod' import Default, {} from 'mod' ``` When using typescript ```js import type Default, {} from 'mod' import type {} from 'mod' ``` When using flow ```js import typeof {} from 'mod' import typeof Default, {} from 'mod' ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-extraneous-dependencies.md # import/no-extraneous-dependencies Forbid the import of external modules that are not declared in the `package.json`'s `dependencies`, `devDependencies`, `optionalDependencies`, `peerDependencies`, or `bundledDependencies`. The closest parent `package.json` will be used. If no `package.json` is found, the rule will not lint anything. This behavior can be changed with the rule option `packageDir`. Normally ignores imports of modules marked internal, but this can be changed with the rule option `includeInternal`. Type imports can be verified by specifying `includeTypes`. Modules have to be installed for this rule to work. ## Options This rule supports the following options: `devDependencies`: If set to `false`, then the rule will show an error when `devDependencies` are imported. Defaults to `true`. Type imports are ignored by default. `optionalDependencies`: If set to `false`, then the rule will show an error when `optionalDependencies` are imported. Defaults to `true`. `peerDependencies`: If set to `false`, then the rule will show an error when `peerDependencies` are imported. Defaults to `true`. `bundledDependencies`: If set to `false`, then the rule will show an error when `bundledDependencies` are imported. Defaults to `true`. You can set the options like this: ```js "import/no-extraneous-dependencies": ["error", {"devDependencies": false, "optionalDependencies": false, "peerDependencies": false}] ``` You can also use an array of globs instead of literal booleans: ```js "import/no-extraneous-dependencies": ["error", {"devDependencies": ["**/*.test.js", "**/*.spec.js"]}] ``` When using an array of globs, the setting will be set to `true` (no errors reported) if the name of the file being linted (i.e. not the imported file/module) matches a single glob in the array, and `false` otherwise. There are 2 boolean options to opt into checking extra imports that are normally ignored: `includeInternal`, which enables the checking of internal modules, and `includeTypes`, which enables checking of type imports in TypeScript. ```js "import/no-extraneous-dependencies": ["error", {"includeInternal": true, "includeTypes": true}] ``` Also there is one more option called `packageDir`, this option is to specify the path to the folder containing package.json. If provided as a relative path string, will be computed relative to the current working directory at linter execution time. If this is not ideal (does not work with some editor integrations), consider using `__dirname` to provide a path relative to your configuration. ```js "import/no-extraneous-dependencies": ["error", {"packageDir": './some-dir/'}] // or "import/no-extraneous-dependencies": ["error", {"packageDir": path.join(__dirname, 'some-dir')}] ``` It may also be an array of multiple paths, to support monorepos or other novel project folder layouts: ```js "import/no-extraneous-dependencies": ["error", {"packageDir": ['./some-dir/', './root-pkg']}] ``` ## Rule Details Given the following `package.json`: ```json { "name": "my-project", "...": "...", "dependencies": { "builtin-modules": "^1.1.1", "lodash.cond": "^4.2.0", "lodash.find": "^4.2.0", "pkg-up": "^1.0.0" }, "devDependencies": { "ava": "^0.13.0", "eslint": "^2.4.0", "eslint-plugin-ava": "^1.3.0", "xo": "^0.13.0" }, "optionalDependencies": { "lodash.isarray": "^4.0.0" }, "peerDependencies": { "react": ">=15.0.0 <16.0.0" }, "bundledDependencies": [ "@generated/foo", ] } ``` ## Fail ```js var _ = require('lodash'); import _ from 'lodash'; import react from 'react'; /* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": false}] */ import test from 'ava'; var test = require('ava'); /* eslint import/no-extraneous-dependencies: ["error", {"optionalDependencies": false}] */ import isArray from 'lodash.isarray'; var isArray = require('lodash.isarray'); /* eslint import/no-extraneous-dependencies: ["error", {"bundledDependencies": false}] */ import foo from '"@generated/foo"'; var foo = require('"@generated/foo"'); /* eslint import/no-extraneous-dependencies: ["error", {"includeInternal": true}] */ import foo from './foo'; var foo = require('./foo'); /* eslint import/no-extraneous-dependencies: ["error", {"includeTypes": true}] */ import type { MyType } from 'foo'; ``` ## Pass ```js // Builtin and internal modules are fine var path = require('path'); var foo = require('./foo'); import test from 'ava'; import find from 'lodash.find'; import isArray from 'lodash.isarray'; import foo from '"@generated/foo"'; import type { MyType } from 'foo'; /* eslint import/no-extraneous-dependencies: ["error", {"peerDependencies": true}] */ import react from 'react'; ``` ## When Not To Use It If you do not have a `package.json` file in your project. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-import-module-exports.md # import/no-import-module-exports πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Reports the use of import declarations with CommonJS exports in any module except for the [main module](https://docs.npmjs.com/files/package.json#main). If you have multiple entry points or are using `js:next` this rule includes an `exceptions` option which you can use to exclude those files from the rule. ## Options ### `exceptions` - An array of globs. The rule will be omitted from any file that matches a glob in the options array. For example, the following setting will omit the rule in the `some-file.js` file. ```json "import/no-import-module-exports": ["error", { "exceptions": ["**/*/some-file.js"] }] ``` ## Rule Details ### Fail ```js import { stuff } from 'starwars' module.exports = thing import * as allThings from 'starwars' exports.bar = thing import thing from 'other-thing' exports.foo = bar import thing from 'starwars' const baz = module.exports = thing console.log(baz) ``` ### Pass Given the following package.json: ```json { "main": "lib/index.js", } ``` ```js import thing from 'other-thing' export default thing const thing = require('thing') module.exports = thing const thing = require('thing') exports.foo = bar import thing from 'otherthing' console.log(thing.module.exports) // in lib/index.js import foo from 'path'; module.exports = foo; // in some-file.js // eslint import/no-import-module-exports: ["error", {"exceptions": ["**/*/some-file.js"]}] import foo from 'path'; module.exports = foo; ``` ### Further Reading - [webpack issue #4039](https://github.com/webpack/webpack/issues/4039) --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-internal-modules.md # import/no-internal-modules Use this rule to prevent importing the submodules of other modules. ## Rule Details This rule has two mutally exclusive options that are arrays of [minimatch/glob patterns](https://github.com/isaacs/node-glob#glob-primer) patterns: - `allow` that include paths and import statements that can be imported with reaching. - `forbid` that exclude paths and import statements that can be imported with reaching. ### Examples Given the following folder structure: ```pt my-project β”œβ”€β”€ actions β”‚ └── getUser.js β”‚ └── updateUser.js β”œβ”€β”€ reducer β”‚ └── index.js β”‚ └── user.js β”œβ”€β”€ redux β”‚ └── index.js β”‚ └── configureStore.js └── app β”‚ └── index.js β”‚ └── settings.js └── entry.js ``` And the .eslintrc file: ```json { ... "rules": { "import/no-internal-modules": [ "error", { "allow": [ "**/actions/*", "source-map-support/*" ], } ] } } ``` The following patterns are considered problems: ```js /** * in my-project/entry.js */ import { settings } from './app/index'; // Reaching to "./app/index" is not allowed import userReducer from './reducer/user'; // Reaching to "./reducer/user" is not allowed import configureStore from './redux/configureStore'; // Reaching to "./redux/configureStore" is not allowed export { settings } from './app/index'; // Reaching to "./app/index" is not allowed export * from './reducer/user'; // Reaching to "./reducer/user" is not allowed ``` The following patterns are NOT considered problems: ```js /** * in my-project/entry.js */ import 'source-map-support/register'; import { settings } from '../app'; import getUser from '../actions/getUser'; export * from 'source-map-support/register'; export { settings } from '../app'; ``` Given the following folder structure: ```pt my-project β”œβ”€β”€ actions β”‚ └── getUser.js β”‚ └── updateUser.js β”œβ”€β”€ reducer β”‚ └── index.js β”‚ └── user.js β”œβ”€β”€ redux β”‚ └── index.js β”‚ └── configureStore.js └── app β”‚ └── index.js β”‚ └── settings.js └── entry.js ``` And the .eslintrc file: ```json { ... "rules": { "import/no-internal-modules": [ "error", { "forbid": [ "**/actions/*", "source-map-support/*" ], } ] } } ``` The following patterns are considered problems: ```js /** * in my-project/entry.js */ import 'source-map-support/register'; import getUser from '../actions/getUser'; export * from 'source-map-support/register'; export getUser from '../actions/getUser'; ``` The following patterns are NOT considered problems: ```js /** * in my-project/entry.js */ import 'source-map-support'; import { getUser } from '../actions'; export * from 'source-map-support'; export { getUser } from '../actions'; ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-mutable-exports.md # import/no-mutable-exports Forbids the use of mutable exports with `var` or `let`. ## Rule Details Valid: ```js export const count = 1 export function getCount() {} export class Counter {} ``` ...whereas here exports will be reported: ```js export let count = 2 export var count = 3 let count = 4 export { count } // reported here ``` ## Functions/Classes Note that exported function/class declaration identifiers may be reassigned, but are not flagged by this rule at this time. They may be in the future, if a reassignment is detected, i.e. ```js // possible future behavior! export class Counter {} // reported here: exported class is reassigned on line [x]. Counter = KitchenSink // not reported here unless you enable no-class-assign // this pre-declaration reassignment is valid on account of function hoisting getCount = function getDuke() {} // not reported here without no-func-assign export function getCount() {} // reported here: exported function is reassigned on line [x]. ``` To prevent general reassignment of these identifiers, exported or not, you may want to enable the following core ESLint rules: - [no-func-assign] - [no-class-assign] [no-func-assign]: https://eslint.org/docs/rules/no-func-assign [no-class-assign]: https://eslint.org/docs/rules/no-class-assign ## When Not To Use It If your environment correctly implements mutable export bindings. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-named-as-default-member.md # import/no-named-as-default-member ⚠️ This rule _warns_ in the following configs: β˜‘οΈ `recommended`, 🚸 `warnings`. Reports use of an exported name as a property on the default export. Rationale: Accessing a property that has a name that is shared by an exported name from the same module is likely to be a mistake. Named import syntax looks very similar to destructuring assignment. It's easy to make the (incorrect) assumption that named exports are also accessible as properties of the default export. Furthermore, [in Babel 5 this is actually how things worked][blog]. This was fixed in Babel 6. Before upgrading an existing codebase to Babel 6, it can be useful to run this lint rule. [blog]: https://kentcdodds.com/blog/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution ## Rule Details Given: ```js // foo.js export default 'foo'; export const bar = 'baz'; ``` ...this would be valid: ```js import foo, {bar} from './foo.js'; ``` ...and the following would be reported: ```js // Caution: `foo` also has a named export `bar`. // Check if you meant to write `import {bar} from './foo.js'` instead. import foo from './foo.js'; const bar = foo.bar; ``` ```js // Caution: `foo` also has a named export `bar`. // Check if you meant to write `import {bar} from './foo.js'` instead. import foo from './foo.js'; const {bar} = foo; ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-named-as-default.md # import/no-named-as-default ⚠️ This rule _warns_ in the following configs: β˜‘οΈ `recommended`, 🚸 `warnings`. Reports use of an exported name as the locally imported name of a default export. Rationale: using an exported name as the name of the default export is likely... - _misleading_: others familiar with `foo.js` probably expect the name to be `foo` - _a mistake_: only needed to import `bar` and forgot the brackets (the case that is prompting this) ## Rule Details Given: ```js // foo.js export default 'foo'; export const bar = 'baz'; ``` ...this would be valid: ```js import foo from './foo.js'; ``` ...and this would be reported: ```js // message: Using exported name 'bar' as identifier for default export. import bar from './foo.js'; ``` For post-ES2015 `export` extensions, this also prevents exporting the default from a referenced module as a name within that module, for the same reasons: ```js // valid: export foo from './foo.js'; // message: Using exported name 'bar' as identifier for default export. export bar from './foo.js'; ``` ## Further Reading - ECMAScript Proposal: [export ns from] - ECMAScript Proposal: [export default from] [export ns from]: https://github.com/leebyron/ecmascript-export-ns-from [export default from]: https://github.com/leebyron/ecmascript-export-default-from --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-named-default.md # import/no-named-default Reports use of a default export as a locally named import. Rationale: the syntax exists to import default exports expressively, let's use it. Note that type imports, as used by [Flow], are always ignored. [Flow]: https://flow.org/ ## Rule Details Given: ```js // foo.js export default 'foo'; export const bar = 'baz'; ``` ...these would be valid: ```js import foo from './foo.js'; import foo, { bar } from './foo.js'; ``` ...and these would be reported: ```js // message: Using exported name 'bar' as identifier for default export. import { default as foo } from './foo.js'; import { default as foo, bar } from './foo.js'; ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-named-export.md # import/no-named-export Prohibit named exports. Mostly an inverse of [`no-default-export`]. [`no-default-export`]: ./no-default-export.md ## Rule Details The following patterns are considered warnings: ```javascript // bad1.js // There is only a single module export and it's a named export. export const foo = 'foo'; ``` ```javascript // bad2.js // There is more than one named export in the module. export const foo = 'foo'; export const bar = 'bar'; ``` ```javascript // bad3.js // There is more than one named export in the module. const foo = 'foo'; const bar = 'bar'; export { foo, bar } ``` ```javascript // bad4.js // There is more than one named export in the module. export * from './other-module' ``` ```javascript // bad5.js // There is a default and a named export. export const foo = 'foo'; const bar = 'bar'; export default 'bar'; ``` The following patterns are not warnings: ```javascript // good1.js // There is only a single module export and it's a default export. export default 'bar'; ``` ```javascript // good2.js // There is only a single module export and it's a default export. const foo = 'foo'; export { foo as default } ``` ```javascript // good3.js // There is only a single module export and it's a default export. export default from './other-module'; ``` ## When Not To Use It If you don't care if named imports are used, or if you prefer named imports over default imports. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-namespace.md # import/no-namespace πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Enforce a convention of not using namespace (a.k.a. "wildcard" `*`) imports. The rule is auto-fixable when the namespace object is only used for direct member access, e.g. `namespace.a`. ## Options This rule supports the following options: - `ignore`: array of glob strings for modules that should be ignored by the rule. ## Rule Details Valid: ```js import defaultExport from './foo' import { a, b } from './bar' import defaultExport, { a, b } from './foobar' ``` ```js /* eslint import/no-namespace: ["error", {ignore: ['*.ext']}] */ import * as bar from './ignored-module.ext'; ``` Invalid: ```js import * as foo from 'foo'; ``` ```js import defaultExport, * as foo from 'foo'; ``` ## When Not To Use It If you want to use namespaces, you don't want to use this rule. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-nodejs-modules.md # import/no-nodejs-modules Forbid the use of Node.js builtin modules. Can be useful for client-side web projects that do not have access to those modules. ## Options This rule supports the following options: - `allow`: Array of names of allowed modules. Defaults to an empty array. ## Rule Details ### Fail ```js import fs from 'fs'; import path from 'path'; var fs = require('fs'); var path = require('path'); ``` ### Pass ```js import _ from 'lodash'; import foo from 'foo'; import foo from './foo'; var _ = require('lodash'); var foo = require('foo'); var foo = require('./foo'); /* eslint import/no-nodejs-modules: ["error", {"allow": ["path"]}] */ import path from 'path'; ``` ## When Not To Use It If you have a project that is run mainly or partially using Node.js. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-relative-packages.md # import/no-relative-packages πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Use this rule to prevent importing packages through relative paths. It's useful in Yarn/Lerna workspaces, where it's possible to import a sibling package using `../package` relative path, while direct `package` is the correct one. ## Examples Given the following folder structure: ```pt my-project β”œβ”€β”€ packages β”‚ β”œβ”€β”€ foo β”‚ β”‚ β”œβ”€β”€ index.js β”‚ β”‚ └── package.json β”‚ └── bar β”‚ β”œβ”€β”€ index.js β”‚ └── package.json └── entry.js ``` And the .eslintrc file: ```json { ... "rules": { "import/no-relative-packages": "error" } } ``` The following patterns are considered problems: ```js /** * in my-project/packages/foo.js */ import bar from '../bar'; // Import sibling package using relative path import entry from '../../entry.js'; // Import from parent package using relative path /** * in my-project/entry.js */ import bar from './packages/bar'; // Import child package using relative path ``` The following patterns are NOT considered problems: ```js /** * in my-project/packages/foo.js */ import bar from 'bar'; // Import sibling package using package name /** * in my-project/entry.js */ import bar from 'bar'; // Import sibling package using package name ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-relative-parent-imports.md # import/no-relative-parent-imports Use this rule to prevent imports to folders in relative parent paths. This rule is useful for enforcing tree-like folder structures instead of complex graph-like folder structures. While this restriction might be a departure from Node's default resolution style, it can lead large, complex codebases to be easier to maintain. If you've ever had debates over "where to put files" this rule is for you. To fix violations of this rule there are three general strategies. Given this example: ```pt numbers └── three.js add.js ``` ```js // ./add.js export default function (numbers) { return numbers.reduce((sum, n) => sum + n, 0); } // ./numbers/three.js import add from '../add'; // violates import/no-relative-parent-imports export default function three() { return add([1, 2]); } ``` You can, 1. Move the file to be in a sibling folder (or higher) of the dependency. `three.js` could be be in the same folder as `add.js`: ```pt three.js add.js ``` or since `add` doesn't have any imports, it could be in it's own directory (namespace): ```pt math └── add.js three.js ``` 2. Pass the dependency as an argument at runtime (dependency injection) ```js // three.js export default function three(add) { return add([1, 2]); } // somewhere else when you use `three.js`: import add from './add'; import three from './numbers/three'; console.log(three(add)); ``` 3. Make the dependency a package so it's globally available to all files in your project: ```js import add from 'add'; // from https://www.npmjs.com/package/add export default function three() { return add([1,2]); } ``` These are (respectively) static, dynamic & global solutions to graph-like dependency resolution. ## Examples Given the following folder structure: ```pt my-project β”œβ”€β”€ lib β”‚ β”œβ”€β”€ a.js β”‚ └── b.js └── main.js ``` And the .eslintrc file: ```json { ... "rules": { "import/no-relative-parent-imports": "error" } } ``` The following patterns are considered problems: ```js /** * in my-project/lib/a.js */ import bar from '../main'; // Import parent file using a relative path ``` The following patterns are NOT considered problems: ```js /** * in my-project/main.js */ import foo from 'foo'; // Import package using module path import a from './lib/a'; // Import child file using relative path /** * in my-project/lib/a.js */ import b from './b'; // Import sibling file using relative path ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-restricted-paths.md # import/no-restricted-paths Some projects contain files which are not always meant to be executed in the same environment. For example consider a web application that contains specific code for the server and some specific code for the browser/client. In this case you don’t want to import server-only files in your client code. In order to prevent such scenarios this rule allows you to define restricted zones where you can forbid files from being imported if they match a specific path. ## Rule Details This rule has one option, which is an object containing all `zones` where restrictions will be applied, plus an optional `basePath` used to resolve relative paths within each zone. The default for `basePath` is the current working directory. Each zone consists of a `target`, a `from`, and optional `except` and `message` attributes. - `target` - Identifies which files are part of the zone. It can be expressed as: - A simple directory path, matching all files contained recursively within it - A glob pattern - An array of any of the two types above - *Example: `target: './client'` - this zone consists of all files under the 'client' dir* - `from` - Identifies folders from which the zone is not allowed to import. It can be expressed as: - A simple directory path, matching all files contained recursively within it - A glob pattern - An array of only simple directories, or of only glob patterns (mixing both types within the array is not allowed) - *Example: `from: './server'` - this zone is not allowed to import anything from the 'server' dir* - `except` - Optional. Allows exceptions that would otherwise violate the related `from`. Note that it does not alter the behaviour of `target` in any way. - If `from` is an array of glob patterns, `except` must be an array of glob patterns as well. - If `from` is an array of simple directories, `except` is relative to `from` and cannot backtrack to a parent directory. - *Example: `except: './server/config'` this zone is allowed to import server config, even if it can't import other server code* - `message` - Optional. Displayed in case of rule violation. *Note: The `from` attribute is NOT matched literally against the import path string as it appears in the code. Instead, it's matched against the path to the imported file after it's been resolved against `basePath`.* ### Examples Given this folder structure: ```pt . β”œβ”€β”€ client β”‚ β”œβ”€β”€ foo.js β”‚ └── baz.js └── server └── bar.js ``` And this configuration: ```json { "zones": [ { "target": "./client", "from": "./server" } ] } ``` :x: The following is considered incorrect: ```js // client/foo.js import bar from '../server/bar'; ``` :white_check_mark: The following is considered correct: ```js // server/bar.js import baz from '../client/baz'; ``` --------------- Given this folder structure: ```pt . β”œβ”€β”€ client β”‚ └── ... └── server β”œβ”€β”€ one β”‚ β”œβ”€β”€ a.js β”‚ └── b.js └── two └── a.js ``` And this configuration: ```json { "zones": [ { "target": "./server/one", "from": "./server", "except": ["./one"] } ] } ``` :x: The following is considered incorrect: ```js // server/one/a.js import a from '../two/a' ``` :white_check_mark: The following is considered correct: ```js // server/one/a.js import b from './b' ``` --------------- Given this folder structure: ```pt . └── client β”œβ”€β”€ foo.js └── sub-module β”œβ”€β”€ bar.js └── baz.js ``` And this configuration: ```json { "zones": [ { "target": "./client/!(sub-module)/**/*", "from": "./client/sub-module/**/*", } ] } ``` :x: The following is considered incorrect: ```js // client/foo.js import a from './sub-module/baz' ``` :white_check_mark: The following is considered correct: ```js // client/sub-module/bar.js import b from './baz' ``` --------------- Given this folder structure: ```pt . β”œβ”€β”€ one β”‚ β”œβ”€β”€ a.js β”‚ └── b.js β”œβ”€β”€ two β”‚ β”œβ”€β”€ a.js β”‚ └── b.js └── three β”œβ”€β”€ a.js └── b.js ``` And this configuration: ```json { "zones": [ { "target": [ "./two/*", "./three/*" ], "from": [ "./one", "./three" ] } ] } ``` :white_check_mark: The following is considered correct: ```js // one/b.js import a from '../three/a' import a from './a' ``` ```js // two/b.js import a from './a' ``` :x: The following is considered incorrect: ```js // two/a.js import a from '../one/a' import a from '../three/a' ``` ```js // three/b.js import a from '../one/a' import a from './a' ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-self-import.md # import/no-self-import Forbid a module from importing itself. This can sometimes happen during refactoring. ## Rule Details ### Fail ```js // foo.js import foo from './foo'; const foo = require('./foo'); ``` ```js // index.js import index from '.'; const index = require('.'); ``` ### Pass ```js // foo.js import bar from './bar'; const bar = require('./bar'); ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-unassigned-import.md # import/no-unassigned-import With both CommonJS' `require` and the ES6 modules' `import` syntax, it is possible to import a module but not to use its result. This can be done explicitly by not assigning the module to as variable. Doing so can mean either of the following things: - The module is imported but not used - The module has side-effects (like [`should`](https://www.npmjs.com/package/should)). Having side-effects, makes it hard to know whether the module is actually used or can be removed. It can also make it harder to test or mock parts of your application. This rule aims to remove modules with side-effects by reporting when a module is imported but not assigned. ## Options This rule supports the following option: `allow`: An Array of globs. The files that match any of these patterns would be ignored/allowed by the linter. This can be useful for some build environments (e.g. css-loader in webpack). Note that the globs start from the where the linter is executed (usually project root), but not from each file that includes the source. Learn more in both the pass and fail examples below. ## Fail ```js import 'should' require('should') // In /src/app.js import '../styles/app.css' // {"allow": ["styles/*.css"]} ``` ## Pass ```js import _ from 'foo' import _, {foo} from 'foo' import _, {foo as bar} from 'foo' import {foo as bar} from 'foo' import * as _ from 'foo' const _ = require('foo') const {foo} = require('foo') const {foo: bar} = require('foo') const [a, b] = require('foo') const _ = require('foo') // Module is not assigned, but it is used bar(require('foo')) require('foo').bar require('foo').bar() require('foo')() // With allow option set import './style.css' // {"allow": ["**/*.css"]} import 'babel-register' // {"allow": ["babel-register"]} // In /src/app.js import './styles/app.css' import '../scripts/register.js' // {"allow": ["src/styles/**", "**/scripts/*.js"]} ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-unresolved.md # import/no-unresolved πŸ’Ό This rule is enabled in the following configs: ❗ `errors`, β˜‘οΈ `recommended`. Ensures an imported module can be resolved to a module on the local filesystem, as defined by standard Node `require.resolve` behavior. See [settings](../../README.md#settings) for customization options for the resolution (i.e. additional filetypes, `NODE_PATH`, etc.) This rule can also optionally report on unresolved modules in CommonJS `require('./foo')` calls and AMD `require(['./foo'], function (foo) {...})` and `define(['./foo'], function (foo) {...})`. To enable this, send `{ commonjs: true/false, amd: true/false }` as a rule option. Both are disabled by default. If you are using Webpack, see the section on [resolvers](../../README.md#resolvers). ## Rule Details ### Options By default, only ES6 imports will be resolved: ```js /*eslint import/no-unresolved: 2*/ import x from './foo' // reports if './foo' cannot be resolved on the filesystem ``` If `{commonjs: true}` is provided, single-argument `require` calls will be resolved: ```js /*eslint import/no-unresolved: [2, { commonjs: true }]*/ const { default: x } = require('./foo') // reported if './foo' is not found require(0) // ignored require(['x', 'y'], function (x, y) { /*...*/ }) // ignored ``` Similarly, if `{ amd: true }` is provided, dependency paths for `define` and `require` calls will be resolved: ```js /*eslint import/no-unresolved: [2, { amd: true }]*/ define(['./foo'], function (foo) { /*...*/ }) // reported if './foo' is not found require(['./foo'], function (foo) { /*...*/ }) // reported if './foo' is not found const { default: x } = require('./foo') // ignored ``` Both may be provided, too: ```js /*eslint import/no-unresolved: [2, { commonjs: true, amd: true }]*/ const { default: x } = require('./foo') // reported if './foo' is not found define(['./foo'], function (foo) { /*...*/ }) // reported if './foo' is not found require(['./foo'], function (foo) { /*...*/ }) // reported if './foo' is not found ``` #### `ignore` This rule has its own ignore list, separate from [`import/ignore`]. This is because you may want to know whether a module can be located, regardless of whether it can be parsed for exports: `node_modules`, CoffeeScript files, etc. are all good to resolve properly, but will not be parsed if configured as such via [`import/ignore`]. To suppress errors from files that may not be properly resolved by your [resolver settings](../../README.md#resolver-plugins), you may add an `ignore` key with an array of `RegExp` pattern strings: ```js /*eslint import/no-unresolved: [2, { ignore: ['\\.img$'] }]*/ import { x } from './mod' // may be reported, if not resolved to a module import coolImg from '../../img/coolImg.img' // will not be reported, even if not found ``` #### `caseSensitive` By default, this rule will report paths whose case do not match the underlying filesystem path, if the FS is not case-sensitive. To disable this behavior, set the `caseSensitive` option to `false`. ```js /*eslint import/no-unresolved: [2, { caseSensitive: true (default) | false }]*/ const { default: x } = require('./foo') // reported if './foo' is actually './Foo' and caseSensitive: true ``` #### `caseSensitiveStrict` The `caseSensitive` option does not detect case for the current working directory. The `caseSensitiveStrict` option allows checking `cwd` in resolved path. By default, the option is disabled. ```js /*eslint import/no-unresolved: [2, { caseSensitiveStrict: true }]*/ // Absolute paths import Foo from `/Users/fOo/bar/file.js` // reported, /Users/foo/bar/file.js import Foo from `d:/fOo/bar/file.js` // reported, d:/foo/bar/file.js // Relative paths, cwd is Users/foo/ import Foo from `./../fOo/bar/file.js` // reported ``` ## When Not To Use It If you're using a module bundler other than Node or Webpack, you may end up with a lot of false positive reports of missing dependencies. ## Further Reading - [Resolver plugins](../../README.md#resolvers) - [Node resolver](https://npmjs.com/package/eslint-import-resolver-node) (default) - [Webpack resolver](https://npmjs.com/package/eslint-import-resolver-webpack) - [`import/ignore`] global setting [`import/ignore`]: ../../README.md#importignore --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-unused-modules.md # import/no-unused-modules Reports: - modules without any exports - individual exports not being statically `import`ed or `require`ed from other modules in the same project - dynamic imports are supported if argument is a literal string ## Rule Details ### Usage In order for this plugin to work, at least one of the options `missingExports` or `unusedExports` must be enabled (see "Options" section below). In the future, these options will be enabled by default (see ) Example: ```json "rules": { ...otherRules, "import/no-unused-modules": [1, {"unusedExports": true}] } ``` ### Options This rule takes the following option: - **`missingExports`**: if `true`, files without any exports are reported (defaults to `false`) - **`unusedExports`**: if `true`, exports without any static usage within other modules are reported (defaults to `false`) - **`ignoreUnusedTypeExports`**: if `true`, TypeScript type exports without any static usage within other modules are reported (defaults to `false` and has no effect unless `unusedExports` is `true`) - **`src`**: an array with files/paths to be analyzed. It only applies to unused exports. Defaults to `process.cwd()`, if not provided - **`ignoreExports`**: an array with files/paths for which unused exports will not be reported (e.g module entry points in a published package) ### Example for missing exports #### The following will be reported ```js const class MyClass { /*...*/ } function makeClass() { return new MyClass(...arguments) } ``` #### The following will not be reported ```js export default function () { /*...*/ } ``` ```js export const foo = function () { /*...*/ } ``` ```js export { foo, bar } ``` ```js export { foo as bar } ``` ### Example for unused exports given file-f: ```js import { e } from 'file-a' import { f } from 'file-b' import * as fileC from 'file-c' export { default, i0 } from 'file-d' // both will be reported export const j = 99 // will be reported ``` and file-d: ```js export const i0 = 9 // will not be reported export const i1 = 9 // will be reported export default () => {} // will not be reported ``` and file-c: ```js export const h = 8 // will not be reported export default () => {} // will be reported, as export * only considers named exports and ignores default exports ``` and file-b: ```js import two, { b, c, doAnything } from 'file-a' export const f = 6 // will not be reported ``` and file-a: ```js const b = 2 const c = 3 const d = 4 export const a = 1 // will be reported export { b, c } // will not be reported export { d as e } // will not be reported export function doAnything() { // some code } // will not be reported export default 5 // will not be reported ``` ### Unused exports with `ignoreUnusedTypeExports` set to `true` The following will not be reported: ```ts export type Foo = {}; // will not be reported export interface Foo = {}; // will not be reported export enum Foo {}; // will not be reported ``` #### Important Note Exports from files listed as a main file (`main`, `browser`, or `bin` fields in `package.json`) will be ignored by default. This only applies if the `package.json` is not set to `private: true` ## When not to use If you don't mind having unused files or dead code within your codebase, you can disable this rule --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-useless-path-segments.md # import/no-useless-path-segments πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Use this rule to prevent unnecessary path segments in import and require statements. ## Rule Details Given the following folder structure: ```pt my-project β”œβ”€β”€ app.js β”œβ”€β”€ footer.js β”œβ”€β”€ header.js └── helpers.js └── helpers └── index.js β”œβ”€β”€ index.js └── pages β”œβ”€β”€ about.js β”œβ”€β”€ contact.js └── index.js ``` The following patterns are considered problems: ```js /** * in my-project/app.js */ import "./../my-project/pages/about.js"; // should be "./pages/about.js" import "./../my-project/pages/about"; // should be "./pages/about" import "../my-project/pages/about.js"; // should be "./pages/about.js" import "../my-project/pages/about"; // should be "./pages/about" import "./pages//about"; // should be "./pages/about" import "./pages/"; // should be "./pages" import "./pages/index"; // should be "./pages" (except if there is a ./pages.js file) import "./pages/index.js"; // should be "./pages" (except if there is a ./pages.js file) ``` The following patterns are NOT considered problems: ```js /** * in my-project/app.js */ import "./header.js"; import "./pages"; import "./pages/about"; import "."; import ".."; import fs from "fs"; ``` ## Options ### noUselessIndex If you want to detect unnecessary `/index` or `/index.js` (depending on the specified file extensions, see below) imports in your paths, you can enable the option `noUselessIndex`. By default it is set to `false`: ```js "import/no-useless-path-segments": ["error", { noUselessIndex: true, }] ``` Additionally to the patterns described above, the following imports are considered problems if `noUselessIndex` is enabled: ```js // in my-project/app.js import "./helpers/index"; // should be "./helpers/" (not auto-fixable to `./helpers` because this would lead to an ambiguous import of `./helpers.js` and `./helpers/index.js`) import "./pages/index"; // should be "./pages" (auto-fixable) import "./pages/index.js"; // should be "./pages" (auto-fixable) ``` Note: `noUselessIndex` only avoids ambiguous imports for `.js` files if you haven't specified other resolved file extensions. See [Settings: import/extensions](https://github.com/import-js/eslint-plugin-import#importextensions) for details. ### commonjs When set to `true`, this rule checks CommonJS imports. Default to `false`. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-webpack-loader-syntax.md # import/no-webpack-loader-syntax Forbid Webpack loader syntax in imports. [Webpack](https://webpack.js.org) allows specifying the [loaders](https://webpack.js.org/concepts/loaders/) to use in the import source string using a special syntax like this: ```js var moduleWithOneLoader = require("my-loader!./my-awesome-module"); ``` This syntax is non-standard, so it couples the code to Webpack. The recommended way to specify Webpack loader configuration is in a [Webpack configuration file](https://webpack.js.org/concepts/loaders/#configuration). ## Rule Details ### Fail ```js import myModule from 'my-loader!my-module'; import theme from 'style!css!./theme.css'; var myModule = require('my-loader!./my-module'); var theme = require('style!css!./theme.css'); ``` ### Pass ```js import myModule from 'my-module'; import theme from './theme.css'; var myModule = require('my-module'); var theme = require('./theme.css'); ``` ## When Not To Use It If you have a project that doesn't use Webpack you can safely disable this rule. --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/order.md # import/order πŸ”§ This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix). Enforce a convention in the order of `require()` / `import` statements. 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 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][3] for further details on how imports are grouped. ## Fail ```ts 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 ``` ## Pass ```ts 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'); ``` ## Limitations of `--fix` 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. ```javascript 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. ```javascript import 'format1.css'; // OK import b from 'b' import a from 'a' import 'format2.css'; // OK ``` ## Options This rule supports the following options (none of which are required): - [`groups`][18] - [`pathGroups`][8] - [`pathGroupsExcludedImportTypes`][9] - [`distinctGroup`][32] - [`newlines-between`][20] - [`alphabetize`][30] - [`named`][33] - [`warnOnUnassignedImports`][5] - [`sortTypesGroup`][7] - [`newlines-between-types`][27] - [`consolidateIslands`][25] --- ### `groups` 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. #### Example ```jsonc { "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 ], }], } ``` #### How Imports Are Grouped An import (a `ImportDeclaration`, `TSImportEqualsDeclaration`, or `require()` `CallExpression`) is grouped by its type (`"require"` vs `"import"`), its [specifier][4], and any corresponding identifiers. ```ts import { identifier1, identifier2 } from 'specifier1'; import type { MyType } from 'specifier2'; const identifier3 = require('specifier3'); ``` 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 [`sortTypesGroup`][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 [`sortTypesGroup`][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": "~/**", // The predefined group this PathGroup is defined in relation to "group": "external", // How matching imports will be positioned relative to "group" "position": "after" } ] }] } ``` ### `pathGroupsExcludedImportTypes` Valid values: `("builtin" | "external" | "internal" | "unknown" | "parent" | "sibling" | "index" | "object" | "type")[]` \ Default: `["builtin", "external", "object"]` 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. > [!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 ```jsonc { "import/order": ["error", { "pathGroups": [ { "pattern": "@app/**", "group": "external", "position": "after" } ], "pathGroupsExcludedImportTypes": ["builtin"] }] } ``` ### `distinctGroup` 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`][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. 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]. 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" } ] }] } ``` ### `newlines-between` 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][21], or a tool like [Prettier][22], 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 #### 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 sibling from './foo'; import index from './'; ``` ```ts /* 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 './'; ``` ```ts /* 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: ```ts /* eslint import/order: ["error", {"newlines-between": "always"}] */ import fs from 'fs'; import path from 'path'; import sibling from './foo'; import index from './'; ``` ```ts /* 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 './'; ``` ```ts /* eslint import/order: ["error", {"newlines-between": "never"}] */ import fs from 'fs'; import path from 'path'; import sibling from './foo'; import index from './'; ``` ### `alphabetize` 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][18] or [`PathGroup`][8] 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][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"; ``` - `export`: ```ts export { Readline }; // and export { Readline } from "readline"; ``` - `require`: ```ts const { Readline } = require("readline"); ``` - `cjsExports`: ```ts 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][23] (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 first - `types-last`: forces type-only identifiers to occur last - `mixed`: sorts all identifiers in alphabetical order #### Example Given the following settings: ```jsonc { "import/order": ["error", { "named": true, "alphabetize": { "order": "asc" } }] } ``` This will fail the rule check: ```ts import { compose, apply } from 'xcompose'; ``` While this will pass: ```ts import { apply, compose } from 'xcompose'; ``` ### `warnOnUnassignedImports` 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][31], > and changing the order of such imports cannot be done safely. #### Example Given the following settings: ```jsonc { "import/order": ["error", { "warnOnUnassignedImports": true }] } ``` This will fail the rule check: ```ts import fs from 'fs'; import './styles.css'; import path from 'path'; ``` While this will pass: ```ts import fs from 'fs'; import path from 'path'; import './styles.css'; ``` ### `sortTypesGroup` 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. 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. #### 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 `sortTypesGroup` to `true`: ```jsonc { "import/order": ["error", { "groups": ["type", "builtin", "parent", "sibling", "index"], "alphabetize": { "order": "asc" }, "sortTypesGroup": 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 [`sortTypesGroup`][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 [`sortTypesGroup`][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"], "sortTypesGroup": true, "newlines-between": "always" }] } ``` This will fail the rule check: ```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 "./"; ``` However, if we set `newlines-between-types` to `"ignore"`: ```jsonc { "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`][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"], "sortTypesGroup": true, "newlines-between": "never", "newlines-between-types": "always" }] } ``` ```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 "./"; ``` 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"], "sortTypesGroup": 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` Valid values: `"inside-groups" | "never"` \ Default: `"never"` > [!NOTE] > > This setting is only meaningful when [`newlines-between`][20] and/or [`newlines-between-types`][27] 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][18] or [`pathGroups`][8]. > [!IMPORTANT] > > When all of the following are true: > > - [`sortTypesGroup`][7] is set to `true` > - `consolidateIslands` is set to `"inside-groups"` > - [`newlines-between`][20] is set to `"always-and-inside-groups"` when [`newlines-between-types`][27] is set to `"never"` (or vice-versa) > > Then [`newlines-between`][20]/[`newlines-between-types`][27] will yield to > `consolidateIslands` and 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. #### 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": [], "sortTypesGroup": 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/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]: #sorttypesgroup [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 --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/prefer-default-export.md # import/prefer-default-export In exporting files, this rule checks if there is default export or not. ## Rule Details ### rule schema ```javascript "import/prefer-default-export": [ ( "off" | "warn" | "error" ), { "target": "single" | "any" } // default is "single" ] ``` ### Config Options There are two options available: `single` and `any`. By default, if you do not specify the option, rule will assume it is `single`. #### single **Definition**: When there is only a single export from a module, prefer using default export over named export. How to setup config file for this rule: ```javascript // you can manually specify it "rules": { "import/prefer-default-export": [ ( "off" | "warn" | "error" ), { "target": "single" } ] } // config setup below will also work "rules": { "import/prefer-default-export": "off" | "warn" | "error" } ``` The following patterns are considered warnings: ```javascript // bad.js // There is only a single module export and it's a named export. export const foo = 'foo'; ``` The following patterns are not warnings: ```javascript // good1.js // There is a default export. export const foo = 'foo'; const bar = 'bar'; export default bar; ``` ```javascript // good2.js // There is more than one named export in the module. export const foo = 'foo'; export const bar = 'bar'; ``` ```javascript // good3.js // There is more than one named export in the module const foo = 'foo'; const bar = 'bar'; export { foo, bar } ``` ```javascript // good4.js // There is a default export. const foo = 'foo'; export { foo as default } ``` ```javascript // export-star.js // Any batch export will disable this rule. The remote module is not inspected. export * from './other-module' ``` #### any **Definition**: any exporting file must contain a default export. How to setup config file for this rule: ```javascript // you have to manually specify it "rules": { "import/prefer-default-export": [ ( "off" | "warn" | "error" ), { "target": "any" } ] } ``` The following patterns are *not* considered warnings: ```javascript // good1.js //has default export export default function bar() {}; ``` ```javascript // good2.js // has default export let foo; export { foo as default } ``` ```javascript // good3.js //contains multiple exports AND default export export const a = 5; export function bar(){}; let foo; export { foo as default } ``` ```javascript // good4.js // does not contain any exports => file is not checked by the rule import * as foo from './foo';ο»Ώ ``` ```javascript // export-star.js // Any batch export will disable this rule. The remote module is not inspected. export * from './other-module' ``` The following patterns are considered warnings: ```javascript // bad1.js //has 2 named exports, but no default export export const foo = 'foo'; export const bar = 'bar'; ``` ```javascript // bad2.js // does not have default export let foo, bar; export { foo, bar } ``` ```javascript // bad3.js // does not have default export export { a, b } from "foo.js"ο»Ώ ``` ```javascript // bad4.js // does not have default export let item; export const foo = item; export { item }; ``` --- # Source: https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/unambiguous.md # import/unambiguous Warn if a `module` could be mistakenly parsed as a `script` by a consumer leveraging [Unambiguous JavaScript Grammar] to determine correct parsing goal. Will respect the [`parserOptions.sourceType`] from ESLint config, i.e. files parsed as `script` per that setting will not be reported. This plugin uses [Unambiguous JavaScript Grammar] internally to decide whether dependencies should be parsed as modules and searched for exports matching the `import`ed names, so it may be beneficial to keep this rule on even if your application will run in an explicit `module`-only environment. ## Rule Details For files parsed as `module` by ESLint, the following are valid: ```js import 'foo' function x() { return 42 } ``` ```js export function x() { return 42 } ``` ```js (function x() { return 42 })() export {} // simple way to mark side-effects-only file as 'module' without any imports/exports ``` ...whereas the following file would be reported: ```js (function x() { return 42 })() ``` ## When Not To Use It If your application environment will always know via [some other means](https://github.com/nodejs/node-eps/issues/13) how to parse, regardless of syntax, you may not need this rule. Remember, though, that this plugin uses this strategy internally, so if you were to `import` from a module with no `import`s or `export`s, this plugin would not report it as it would not be clear whether it should be considered a `script` or a `module`. ## Further Reading - [Unambiguous JavaScript Grammar] - [`parserOptions.sourceType`] - [node-eps#13](https://github.com/nodejs/node-eps/issues/13) [`parserOptions.sourceType`]: https://eslint.org/docs/user-guide/configuring#specifying-parser-options [Unambiguous JavaScript Grammar]: https://github.com/nodejs/node-eps/blob/HEAD/002-es-modules.md#32-determining-if-source-is-an-es-module