0.2.0 - Mid migration

This commit is contained in:
Daniel Mason 2022-04-25 14:47:15 +12:00
parent 139e6a915e
commit 7e38fdbd7d
42393 changed files with 5358157 additions and 62 deletions

View file

@ -0,0 +1,71 @@
# import/default
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

View file

@ -0,0 +1,85 @@
# dynamic imports require a leading comment with a webpackChunkName (dynamic-import-chunkname)
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
{
"dynamic-import-chunkname": [2, {
importFunctions: ["dynamicImport"],
webpackChunknameFormat: "[a-zA-Z0-57-9-/_]+"
}]
}
```
### 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',
);
```
### 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',
);
```
## 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.

View file

@ -0,0 +1,32 @@
# import/export
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

View file

@ -0,0 +1,50 @@
# 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.

View file

@ -0,0 +1,163 @@
# import/extensions - Ensure consistent use of file extension within the import path
Some file resolve algorithms allow you to omit the file extension within the import source path. For example the `node` resolver can resolve `./foo/bar` to the absolute path `/User/someone/foo/bar.js` because the `.js` extension is resolved automatically by default. 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.
```
"import/extensions": [<severity>, "never" | "always" | "ignorePackages"]
```
By providing an object you can configure each extension separately.
```
"import/extensions": [<severity>, {
<extension>: "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.
```
"import/extensions": [
<severity>,
"never" | "always" | "ignorePackages",
{
<extension>: "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:
```
"import/extensions": [
<severity>,
"never" | "always" | "ignorePackages",
{
ignorePackages: true | false,
pattern: {
<extension>: "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`.
### 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:
```
├── foo
│   ├── bar.js
│   ├── bar.json
```
and this import statement:
```js
import bar from './foo/bar.json';
```
then the extension cant 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 configuration set to "always":
```js
import foo from './foo';
import bar from './bar';
import Component from './Component';
```
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';
```
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';
```
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';
```
## When Not To Use It
If you are not concerned about a consistent usage of file extension.

View file

@ -0,0 +1,70 @@
# import/first
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](http://www.ecma-international.org/ecma-262/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

View file

@ -0,0 +1,117 @@
# 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
```
```flow js
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
```
```flow js
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.

View file

@ -0,0 +1,3 @@
# imports-first
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/master/docs/rules/first.md).

View file

@ -0,0 +1,44 @@
# 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 takes the following option:
`max`: 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.
You can set the option like this:
```js
"import/max-dependencies": ["error", {"max": 10}]
```
## Example
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
```
## When Not To Use It
If you don't care how many dependencies a module has.

View file

@ -0,0 +1,100 @@
# import/named
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

View file

@ -0,0 +1,99 @@
# import/namespace
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

View file

@ -0,0 +1,87 @@
# import/newline-after-import
Enforces having one or more empty lines after the last top-level import statement or require call.
+(fixable) The `--fix` option on the [command line] automatically fixes problems reported by this rule.
## Rule Details
This rule has one option, `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`.
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'
```
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'
```
## 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.

View file

@ -0,0 +1,48 @@
# import/no-absolute-path: Forbid import of modules using absolute paths
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.
## 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`
```

View file

@ -0,0 +1,35 @@
# 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: https://github.com/xjamundx/eslint-plugin-modules

View file

@ -0,0 +1,73 @@
# 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
"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 {}
```
### 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 {}
```

View file

@ -0,0 +1,95 @@
# 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: https://github.com/xjamundx/eslint-plugin-modules

View file

@ -0,0 +1,92 @@
# 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`].
## 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.
## 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

View file

@ -0,0 +1,63 @@
# `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.

View file

@ -0,0 +1,61 @@
# `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

View file

@ -0,0 +1,69 @@
# import/no-duplicates
Reports if a resolved path is imported more than once.
+(fixable) The `--fix` option on the [command line] automatically fixes some problems reported by this rule.
ESLint core has a similar rule ([`no-duplicate-imports`](http://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'
```
## 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.

View file

@ -0,0 +1,23 @@
# import/no-dynamic-require: Forbid `require()` calls with expressions
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 checks 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`);
```

View file

@ -0,0 +1,124 @@
# import/no-extraneous-dependencies: Forbid the use of extraneous packages
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`.
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`.
`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 matches a single glob in the array, and `false` otherwise.
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"');
```
## 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"';
/* 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.

View file

@ -0,0 +1,74 @@
# no-import-module-exports
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)

View file

@ -0,0 +1,132 @@
# 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:
```
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:
```
{
...
"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:
```
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:
```
{
...
"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';
```

View file

@ -0,0 +1,52 @@
# 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]: http://eslint.org/docs/rules/no-func-assign
[no-class-assign]: http://eslint.org/docs/rules/no-class-assign
## When Not To Use It
If your environment correctly implements mutable export bindings.

View file

@ -0,0 +1,47 @@
# import/no-named-as-default-member
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;
```

View file

@ -0,0 +1,46 @@
# import/no-named-as-default
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

View file

@ -0,0 +1,31 @@
# 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';
```

View file

@ -0,0 +1,77 @@
# `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.

View file

@ -0,0 +1,41 @@
# import/no-namespace
Enforce a convention of not using namespace (a.k.a. "wildcard" `*`) imports.
+(fixable) The `--fix` option on the [command line] automatically fixes problems reported by this rule, provided that the namespace object is only used for direct member access, e.g. `namespace.a`.
The `--fix` functionality for this rule requires ESLint 5 or newer.
### 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.

View file

@ -0,0 +1,40 @@
# import/no-nodejs-modules: No Node.js builtin 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.

View file

@ -0,0 +1,66 @@
# import/no-relative-packages
Use this rule to prevent importing packages through relative paths.
It's useful in Yarn/Lerna workspaces, were 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:
```
my-project
├── packages
│ ├── foo
│ │ ├── index.js
│ │ └── package.json
│ └── bar
│ ├── index.js
│ └── package.json
└── entry.js
```
And the .eslintrc file:
```
{
...
"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
```

View file

@ -0,0 +1,120 @@
# 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:
```
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`:
```
three.js
add.js
```
or since `add` doesn't have any imports, it could be in it's own directory (namespace):
```
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:
```
my-project
├── lib
│ ├── a.js
│ └── b.js
└── main.js
```
And the .eslintrc file:
```
{
...
"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
```

View file

@ -0,0 +1,80 @@
# import/no-restricted-paths: Restrict which files can be imported in a given folder
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 dont 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 imported if they match a specific path.
## Rule Details
This rule has one option. The option is an object containing the definition of all restricted `zones` and the optional `basePath` which is used to resolve relative paths within.
The default value for `basePath` is the current working directory.
Each zone consists of the `target` path and a `from` path. The `target` is the path where the restricted imports should be applied. The `from` path defines the folder that is not allowed to be used in an import. An optional `except` may be defined for a zone, allowing exception paths that would otherwise violate the related `from`. Note that `except` is relative to `from` and cannot backtrack to a parent directory.
You may also specify an optional `message` for a zone, which will be displayed in case of the rule violation.
### Examples
Given the following folder structure:
```
my-project
├── client
│ └── foo.js
│ └── baz.js
└── server
└── bar.js
```
and the current file being linted is `my-project/client/foo.js`.
The following patterns are considered problems when configuration set to `{ "zones": [ { "target": "./client", "from": "./server" } ] }`:
```js
import bar from '../server/bar';
```
The following patterns are not considered problems when configuration set to `{ "zones": [ { "target": "./client", "from": "./server" } ] }`:
```js
import baz from '../client/baz';
```
---------------
Given the following folder structure:
```
my-project
├── client
│ └── foo.js
│ └── baz.js
└── server
├── one
│ └── a.js
│ └── b.js
└── two
```
and the current file being linted is `my-project/server/one/a.js`.
and the current configuration is set to:
```
{ "zones": [ {
"target": "./tests/files/restricted-paths/server/one",
"from": "./tests/files/restricted-paths/server",
"except": ["./one"]
} ] }
```
The following pattern is considered a problem:
```js
import a from '../two/a'
```
The following pattern is not considered a problem:
```js
import b from './b'
```

View file

@ -0,0 +1,30 @@
# Forbid a module from importing itself (`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');
```

View file

@ -0,0 +1,59 @@
# import/no-unassigned-import: Forbid unassigned imports
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 <PROJECT_ROOT>/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 <PROJECT_ROOT>/src/app.js
import './styles/app.css'
import '../scripts/register.js'
// {"allow": ["src/styles/**", "**/scripts/*.js"]}
```

View file

@ -0,0 +1,91 @@
# import/no-unresolved
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
```
## 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#resolver-plugins)
- [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

View file

@ -0,0 +1,107 @@
# 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
Note: dynamic imports are currently not supported.
## Rule Details
### Usage
In order for this plugin to work, 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 https://github.com/import-js/eslint-plugin-import/issues/1324)
Example:
```
"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`)
- `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
```
#### 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

View file

@ -0,0 +1,79 @@
# import/no-useless-path-segments
Use this rule to prevent unnecessary path segments in import and require statements.
## Rule Details
Given the following folder structure:
```
my-project
├── app.js
├── footer.js
├── header.js
└── helpers.js
└── helpers
└── index.js
└── pages
├── about.js
├── contact.js
└── index.js
```
The following patterns are considered problems:
```js
/**
* in my-project/app.js
*/
import "./../pages/about.js"; // should be "./pages/about.js"
import "./../pages/about"; // should be "./pages/about"
import "../pages/about.js"; // should be "./pages/about.js"
import "../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`.

View file

@ -0,0 +1,36 @@
# 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.

View file

@ -0,0 +1,315 @@
# import/order: Enforce a convention in module import order
Enforce a convention in the order of `require()` / `import` statements.
+(fixable) The `--fix` option on the [command line] automatically fixes problems reported by this rule.
With the [`groups`](#groups-array) option set to `["builtin", "external", "internal", "parent", "sibling", "index", "object"]` the order is as shown in the following example:
```js
// 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';
```
Unassigned imports are ignored, as the order they are imported in may be important.
Statements using the ES6 `import` syntax must appear before any `require()` statements.
## Fail
```js
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
```js
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');
```
## Options
This rule supports the following options:
### `groups: [array]`:
How groups are defined, and the order to respect. `groups` must be an array of `string` or [`string`]. The only allowed `string`s are:
`"builtin"`, `"external"`, `"internal"`, `"unknown"`, `"parent"`, `"sibling"`, `"index"`, `"object"`, `"type"`.
The enforced order is the same as the order of each element in a group. Omitted types are implicitly grouped together as the last element. Example:
```js
[
'builtin', // Built-in types are first
['sibling', 'parent'], // Then sibling and parent types. They can be mingled together
'index', // Then the index file
'object',
// Then the rest: internal and external type
]
```
The default value is `["builtin", "external", "parent", "sibling", "index"]`.
You can set the options like this:
```js
"import/order": ["error", {"groups": ["index", "sibling", "parent", "internal", "external", "builtin", "object", "type"]}]
```
### `pathGroups: [array of objects]`:
To be able to group by paths mostly needed with aliases pathGroups can be defined.
Properties of the objects
| property | required | type | description |
|----------------|:--------:|--------|---------------|
| pattern | x | string | minimatch pattern for the paths to be in this group (will not be used for builtins or externals) |
| patternOptions | | object | options for minimatch, default: { nocomment: true } |
| group | x | string | one of the allowed groups, the pathGroup will be positioned relative to this group |
| position | | string | defines where around the group the pathGroup will be positioned, can be 'after' or 'before', if not provided pathGroup will be positioned like the group |
```json
{
"import/order": ["error", {
"pathGroups": [
{
"pattern": "~/**",
"group": "external"
}
]
}]
}
```
### `pathGroupsExcludedImportTypes: [array]`:
This defines import types that are not handled by configured pathGroups.
This is mostly needed when you want to handle path groups that look like external imports.
Example:
```json
{
"import/order": ["error", {
"pathGroups": [
{
"pattern": "@app/**",
"group": "external",
"position": "after"
}
],
"pathGroupsExcludedImportTypes": ["builtin"]
}]
}
```
You can also use `patterns`(e.g., `react`, `react-router-dom`, etc).
Example:
```json
{
"import/order": [
"error",
{
"pathGroups": [
{
"pattern": "react",
"group": "builtin",
"position": "before"
}
],
"pathGroupsExcludedImportTypes": ["react"]
}
]
}
```
The default value is `["builtin", "external"]`.
### `newlines-between: [ignore|always|always-and-inside-groups|never]`:
Enforces or forbids new lines between import groups:
- If set to `ignore`, no errors related to new lines between import groups will be reported (default).
- If set to `always`, at least one new line between each group will be enforced, and new lines inside a group will be forbidden. To prevent multiple lines between imports, core `no-multiple-empty-lines` rule can be used.
- If set to `always-and-inside-groups`, it will act like `always` except newlines are allowed inside import groups.
- If set to `never`, no new lines are allowed in the entire import section.
With the default group setting, the following will be invalid:
```js
/* eslint import/order: ["error", {"newlines-between": "always"}] */
import fs from 'fs';
import path from 'path';
import index from './';
import sibling from './foo';
```
```js
/* eslint import/order: ["error", {"newlines-between": "always-and-inside-groups"}] */
import fs from 'fs';
import path from 'path';
import index from './';
import sibling from './foo';
```
```js
/* eslint import/order: ["error", {"newlines-between": "never"}] */
import fs from 'fs';
import path from 'path';
import index from './';
import sibling from './foo';
```
while those will be valid:
```js
/* eslint import/order: ["error", {"newlines-between": "always"}] */
import fs from 'fs';
import path from 'path';
import index from './';
import sibling from './foo';
```
```js
/* eslint import/order: ["error", {"newlines-between": "always-and-inside-groups"}] */
import fs from 'fs';
import path from 'path';
import index from './';
import sibling from './foo';
```
```js
/* eslint import/order: ["error", {"newlines-between": "never"}] */
import fs from 'fs';
import path from 'path';
import index from './';
import sibling from './foo';
```
### `alphabetize: {order: asc|desc|ignore, caseInsensitive: true|false}`:
Sort the order within each group in alphabetical manner based on **import path**:
- `order`: use `asc` to sort in ascending order, and `desc` to sort in descending order (default: `ignore`).
- `caseInsensitive`: use `true` to ignore case, and `false` to consider case (default: `false`).
Example setting:
```js
alphabetize: {
order: 'asc', /* sort in ascending order. Options: ['ignore', 'asc', 'desc'] */
caseInsensitive: true /* ignore case. Options: [true, false] */
}
```
This will fail the rule check:
```js
/* eslint import/order: ["error", {"alphabetize": {"order": "asc", "caseInsensitive": true}}] */
import React, { PureComponent } from 'react';
import aTypes from 'prop-types';
import { compose, apply } from 'xcompose';
import * as classnames from 'classnames';
import blist from 'BList';
```
While this will pass:
```js
/* eslint import/order: ["error", {"alphabetize": {"order": "asc", "caseInsensitive": true}}] */
import blist from 'BList';
import * as classnames from 'classnames';
import aTypes from 'prop-types';
import React, { PureComponent } from 'react';
import { compose, apply } from 'xcompose';
```
### `warnOnUnassignedImports: true|false`:
* default: `false`
Warns when unassigned imports are out of order. These warning will not be fixed
with `--fix` because unassigned imports are used for side-effects and changing the
import of order of modules with side effects can not be done automatically in a
way that is safe.
This will fail the rule check:
```js
/* eslint import/order: ["error", {"warnOnUnassignedImports": true}] */
import fs from 'fs';
import './styles.css';
import path from 'path';
```
While this will pass:
```js
/* eslint import/order: ["error", {"warnOnUnassignedImports": true}] */
import fs from 'fs';
import path from 'path';
import './styles.css';
```
## Related
- [`import/external-module-folders`] setting
- [`import/internal-regex`] setting
[`import/external-module-folders`]: ../../README.md#importexternal-module-folders
[`import/internal-regex`]: ../../README.md#importinternal-regex

View file

@ -0,0 +1,58 @@
# import/prefer-default-export
When there is only a single export from a module, prefer using default export over named export.
## Rule Details
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'
```

View file

@ -0,0 +1,54 @@
# 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`]: http://eslint.org/docs/user-guide/configuring#specifying-parser-options
[Unambiguous JavaScript Grammar]: https://github.com/nodejs/node-eps/blob/master/002-es-modules.md#32-determining-if-source-is-an-es-module