UNPKG

18.3 kBMarkdownView Raw
1# eslint-plugin-import
2
3[![build status](https://travis-ci.org/benmosher/eslint-plugin-import.svg?branch=master)](https://travis-ci.org/benmosher/eslint-plugin-import)
4[![Coverage Status](https://coveralls.io/repos/github/benmosher/eslint-plugin-import/badge.svg?branch=master)](https://coveralls.io/github/benmosher/eslint-plugin-import?branch=master)
5[![win32 build status](https://ci.appveyor.com/api/projects/status/3mw2fifalmjlqf56/branch/master?svg=true)](https://ci.appveyor.com/project/benmosher/eslint-plugin-import/branch/master)
6[![npm](https://img.shields.io/npm/v/eslint-plugin-import.svg)](https://www.npmjs.com/package/eslint-plugin-import)
7[![npm downloads](https://img.shields.io/npm/dt/eslint-plugin-import.svg?maxAge=2592000)](http://www.npmtrends.com/eslint-plugin-import)
8
9This plugin intends to support linting of ES2015+ (ES6+) import/export syntax, and prevent issues with misspelling of file paths and import names. All the goodness that the ES2015+ static module syntax intends to provide, marked up in your editor.
10
11**IF YOU ARE USING THIS WITH SUBLIME**: see the [bottom section](#sublimelinter-eslint) for important info.
12
13## Rules
14
15### Static analysis
16
17* Ensure imports point to a file/module that can be resolved. ([`no-unresolved`])
18* Ensure named imports correspond to a named export in the remote file. ([`named`])
19* Ensure a default export is present, given a default import. ([`default`])
20* Ensure imported namespaces contain dereferenced properties as they are dereferenced. ([`namespace`])
21* Restrict which files can be imported in a given folder ([`no-restricted-paths`])
22* Forbid import of modules using absolute paths ([`no-absolute-path`])
23* Forbid `require()` calls with expressions ([`no-dynamic-require`])
24* Prevent importing the submodules of other modules ([`no-internal-modules`])
25* Forbid webpack loader syntax in imports ([`no-webpack-loader-syntax`])
26* Forbid a module from importing itself ([`no-self-import`])
27* Forbid a module from importing a module with a dependency path back to itself ([`no-cycle`])
28* Prevent unnecessary path segments in import and require statements ([`no-useless-path-segments`])
29* Forbid importing modules from parent directories ([`no-relative-parent-imports`])
30* Forbid modules without any export, and exports not imported by any modules. ([`no-unused-modules`])
31
32[`no-unresolved`]: ./docs/rules/no-unresolved.md
33[`named`]: ./docs/rules/named.md
34[`default`]: ./docs/rules/default.md
35[`namespace`]: ./docs/rules/namespace.md
36[`no-restricted-paths`]: ./docs/rules/no-restricted-paths.md
37[`no-absolute-path`]: ./docs/rules/no-absolute-path.md
38[`no-dynamic-require`]: ./docs/rules/no-dynamic-require.md
39[`no-internal-modules`]: ./docs/rules/no-internal-modules.md
40[`no-webpack-loader-syntax`]: ./docs/rules/no-webpack-loader-syntax.md
41[`no-self-import`]: ./docs/rules/no-self-import.md
42[`no-cycle`]: ./docs/rules/no-cycle.md
43[`no-useless-path-segments`]: ./docs/rules/no-useless-path-segments.md
44[`no-relative-parent-imports`]: ./docs/rules/no-relative-parent-imports.md
45[`no-unused-modules`]: ./docs/rules/no-unused-modules.md
46
47### Helpful warnings
48
49
50* Report any invalid exports, i.e. re-export of the same name ([`export`])
51* Report use of exported name as identifier of default export ([`no-named-as-default`])
52* Report use of exported name as property of default export ([`no-named-as-default-member`])
53* Report imported names marked with `@deprecated` documentation tag ([`no-deprecated`])
54* Forbid the use of extraneous packages ([`no-extraneous-dependencies`])
55* Forbid the use of mutable exports with `var` or `let`. ([`no-mutable-exports`])
56* Report modules without exports, or exports without matching import in another module ([`no-unused-modules`])
57
58[`export`]: ./docs/rules/export.md
59[`no-named-as-default`]: ./docs/rules/no-named-as-default.md
60[`no-named-as-default-member`]: ./docs/rules/no-named-as-default-member.md
61[`no-deprecated`]: ./docs/rules/no-deprecated.md
62[`no-extraneous-dependencies`]: ./docs/rules/no-extraneous-dependencies.md
63[`no-mutable-exports`]: ./docs/rules/no-mutable-exports.md
64[`no-unused-modules`]: ./docs/rules/no-unused-modules.md
65
66### Module systems
67
68* Report potentially ambiguous parse goal (`script` vs. `module`) ([`unambiguous`])
69* Report CommonJS `require` calls and `module.exports` or `exports.*`. ([`no-commonjs`])
70* Report AMD `require` and `define` calls. ([`no-amd`])
71* No Node.js builtin modules. ([`no-nodejs-modules`])
72
73[`unambiguous`]: ./docs/rules/unambiguous.md
74[`no-commonjs`]: ./docs/rules/no-commonjs.md
75[`no-amd`]: ./docs/rules/no-amd.md
76[`no-nodejs-modules`]: ./docs/rules/no-nodejs-modules.md
77
78
79### Style guide
80
81* Ensure all imports appear before other statements ([`first`])
82* Ensure all exports appear after other statements ([`exports-last`])
83* Report repeated import of the same module in multiple places ([`no-duplicates`])
84* Forbid namespace (a.k.a. "wildcard" `*`) imports ([`no-namespace`])
85* Ensure consistent use of file extension within the import path ([`extensions`])
86* Enforce a convention in module import order ([`order`])
87* Enforce a newline after import statements ([`newline-after-import`])
88* Prefer a default export if module exports a single name ([`prefer-default-export`])
89* Limit the maximum number of dependencies a module can have ([`max-dependencies`])
90* Forbid unassigned imports ([`no-unassigned-import`])
91* Forbid named default exports ([`no-named-default`])
92* Forbid default exports ([`no-default-export`])
93* Forbid named exports ([`no-named-export`])
94* Forbid anonymous values as default exports ([`no-anonymous-default-export`])
95* Prefer named exports to be grouped together in a single export declaration ([`group-exports`])
96* Enforce a leading comment with the webpackChunkName for dynamic imports ([`dynamic-import-chunkname`])
97
98[`first`]: ./docs/rules/first.md
99[`exports-last`]: ./docs/rules/exports-last.md
100[`no-duplicates`]: ./docs/rules/no-duplicates.md
101[`no-namespace`]: ./docs/rules/no-namespace.md
102[`extensions`]: ./docs/rules/extensions.md
103[`order`]: ./docs/rules/order.md
104[`newline-after-import`]: ./docs/rules/newline-after-import.md
105[`prefer-default-export`]: ./docs/rules/prefer-default-export.md
106[`max-dependencies`]: ./docs/rules/max-dependencies.md
107[`no-unassigned-import`]: ./docs/rules/no-unassigned-import.md
108[`no-named-default`]: ./docs/rules/no-named-default.md
109[`no-anonymous-default-export`]: ./docs/rules/no-anonymous-default-export.md
110[`group-exports`]: ./docs/rules/group-exports.md
111[`no-default-export`]: ./docs/rules/no-default-export.md
112[`no-named-export`]: ./docs/rules/no-named-export.md
113[`dynamic-import-chunkname`]: ./docs/rules/dynamic-import-chunkname.md
114
115## Support
116
117[Get supported eslint-plugin-import with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-eslint-plugin-import?utm_source=npm-eslint-plugin-import&utm_medium=referral&utm_campaign=readme)
118
119## Installation
120
121```sh
122npm install eslint-plugin-import -g
123```
124
125or if you manage ESLint as a dev dependency:
126
127```sh
128# inside your project's working tree
129npm install eslint-plugin-import --save-dev
130```
131
132All rules are off by default. However, you may configure them manually
133in your `.eslintrc.(yml|json|js)`, or extend one of the canned configs:
134
135```yaml
136---
137extends:
138 - eslint:recommended
139 - plugin:import/errors
140 - plugin:import/warnings
141
142# or configure manually:
143plugins:
144 - import
145
146rules:
147 import/no-unresolved: [2, {commonjs: true, amd: true}]
148 import/named: 2
149 import/namespace: 2
150 import/default: 2
151 import/export: 2
152 # etc...
153```
154
155# TypeScript
156
157You may use the following shortcut or assemble your own config using the granular settings described below.
158
159Make sure you have installed [`@typescript-eslint/parser`] which is used in the following configuration. Unfortunately NPM does not allow to list optional peer dependencies.
160
161```yaml
162extends:
163 - eslint:recommended
164 - plugin:import/errors
165 - plugin:import/warnings
166 - plugin:import/typescript # this line does the trick
167```
168
169[`@typescript-eslint/parser`]: https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/parser
170
171# Resolvers
172
173With the advent of module bundlers and the current state of modules and module
174syntax specs, it's not always obvious where `import x from 'module'` should look
175to find the file behind `module`.
176
177Up through v0.10ish, this plugin has directly used substack's [`resolve`] plugin,
178which implements Node's import behavior. This works pretty well in most cases.
179
180However, webpack allows a number of things in import module source strings that
181Node does not, such as loaders (`import 'file!./whatever'`) and a number of
182aliasing schemes, such as [`externals`]: mapping a module id to a global name at
183runtime (allowing some modules to be included more traditionally via script tags).
184
185In the interest of supporting both of these, v0.11 introduces resolvers.
186
187Currently [Node] and [webpack] resolution have been implemented, but the
188resolvers are just npm packages, so [third party packages are supported](https://github.com/benmosher/eslint-plugin-import/wiki/Resolvers) (and encouraged!).
189
190You can reference resolvers in several ways (in order of precedence):
191
192- as a conventional `eslint-import-resolver` name, like `eslint-import-resolver-foo`:
193
194```yaml
195# .eslintrc.yml
196settings:
197 # uses 'eslint-import-resolver-foo':
198 import/resolver: foo
199```
200```js
201// .eslintrc.js
202module.exports = {
203 settings: {
204 'import/resolver': {
205 foo: { someConfig: value }
206 }
207 }
208}
209```
210
211- with a full npm module name, like `my-awesome-npm-module`:
212
213```yaml
214# .eslintrc.yml
215settings:
216 import/resolver: 'my-awesome-npm-module'
217```
218```js
219// .eslintrc.js
220module.exports = {
221 settings: {
222 'import/resolver': {
223 'my-awesome-npm-module': { someConfig: value }
224 }
225 }
226}
227```
228
229- with a filesystem path to resolver, defined in this example as a `computed property` name:
230
231```js
232// .eslintrc.js
233module.exports = {
234 settings: {
235 'import/resolver': {
236 [path.resolve('../../../my-resolver')]: { someConfig: value }
237 }
238 }
239}
240```
241
242Relative paths will be resolved relative to the source's nearest `package.json` or
243the process's current working directory if no `package.json` is found.
244
245
246
247If you are interesting in writing a resolver, see the [spec](./resolvers/README.md) for more details.
248
249[`resolve`]: https://www.npmjs.com/package/resolve
250[`externals`]: http://webpack.github.io/docs/library-and-externals.html
251
252[Node]: https://www.npmjs.com/package/eslint-import-resolver-node
253[webpack]: https://www.npmjs.com/package/eslint-import-resolver-webpack
254
255# Settings
256
257You may set the following settings in your `.eslintrc`:
258
259#### `import/extensions`
260
261A list of file extensions that will be parsed as modules and inspected for
262`export`s.
263
264This defaults to `['.js']`, unless you are using the `react` shared config,
265in which case it is specified as `['.js', '.jsx']`.
266
267```js
268"settings": {
269 "import/extensions": [
270 ".js",
271 ".jsx"
272 ]
273}
274```
275
276If you require more granular extension definitions, you can use:
277
278```js
279"settings": {
280 "import/resolver": {
281 "node": {
282 "extensions": [
283 ".js",
284 ".jsx"
285 ]
286 }
287 }
288}
289```
290
291Note that this is different from (and likely a subset of) any `import/resolver`
292extensions settings, which may include `.json`, `.coffee`, etc. which will still
293factor into the `no-unresolved` rule.
294
295Also, the following `import/ignore` patterns will overrule this list.
296
297#### `import/ignore`
298
299A list of regex strings that, if matched by a path, will
300not report the matching module if no `export`s are found.
301In practice, this means rules other than [`no-unresolved`](./docs/rules/no-unresolved.md#ignore) will not report on any
302`import`s with (absolute filesystem) paths matching this pattern.
303
304`no-unresolved` has its own [`ignore`](./docs/rules/no-unresolved.md#ignore) setting.
305
306```yaml
307settings:
308 import/ignore:
309 - \.coffee$ # fraught with parse errors
310 - \.(scss|less|css)$ # can't parse unprocessed CSS modules, either
311```
312
313#### `import/core-modules`
314
315An array of additional modules to consider as "core" modules--modules that should
316be considered resolved but have no path on the filesystem. Your resolver may
317already define some of these (for example, the Node resolver knows about `fs` and
318`path`), so you need not redefine those.
319
320For example, Electron exposes an `electron` module:
321
322```js
323import 'electron' // without extra config, will be flagged as unresolved!
324```
325
326that would otherwise be unresolved. To avoid this, you may provide `electron` as a
327core module:
328
329```yaml
330# .eslintrc.yml
331settings:
332 import/core-modules: [ electron ]
333```
334
335In Electron's specific case, there is a shared config named `electron`
336that specifies this for you.
337
338Contribution of more such shared configs for other platforms are welcome!
339
340#### `import/external-module-folders`
341
342An array of folders. Resolved modules only from those folders will be considered as "external". By default - `["node_modules"]`. Makes sense if you have configured your path or webpack to handle your internal paths differently and want to considered modules from some folders, for example `bower_components` or `jspm_modules`, as "external".
343
344#### `import/parsers`
345
346A map from parsers to file extension arrays. If a file extension is matched, the
347dependency parser will require and use the map key as the parser instead of the
348configured ESLint parser. This is useful if you're inter-op-ing with TypeScript
349directly using webpack, for example:
350
351```yaml
352# .eslintrc.yml
353settings:
354 import/parsers:
355 @typescript-eslint/parser: [ .ts, .tsx ]
356```
357
358In this case, [`@typescript-eslint/parser`](https://www.npmjs.com/package/@typescript-eslint/parser)
359must be installed and require-able from the running `eslint` module's location
360(i.e., install it as a peer of ESLint).
361
362This is currently only tested with `@typescript-eslint/parser` (and its predecessor,
363`typescript-eslint-parser`) but should theoretically work with any moderately
364ESTree-compliant parser.
365
366It's difficult to say how well various plugin features will be supported, too,
367depending on how far down the rabbit hole goes. Submit an issue if you find strange
368behavior beyond here, but steel your heart against the likely outcome of closing
369with `wontfix`.
370
371
372#### `import/resolver`
373
374See [resolvers](#resolvers).
375
376#### `import/cache`
377
378Settings for cache behavior. Memoization is used at various levels to avoid the copious amount of `fs.statSync`/module parse calls required to correctly report errors.
379
380For normal `eslint` console runs, the cache lifetime is irrelevant, as we can strongly assume that files should not be changing during the lifetime of the linter process (and thus, the cache in memory)
381
382For long-lasting processes, like [`eslint_d`] or [`eslint-loader`], however, it's important that there be some notion of staleness.
383
384If you never use [`eslint_d`] or [`eslint-loader`], you may set the cache lifetime to `Infinity` and everything should be fine:
385
386```yaml
387# .eslintrc.yml
388settings:
389 import/cache:
390 lifetime: ∞ # or Infinity
391```
392
393Otherwise, set some integer, and cache entries will be evicted after that many seconds have elapsed:
394
395```yaml
396# .eslintrc.yml
397settings:
398 import/cache:
399 lifetime: 5 # 30 is the default
400```
401
402[`eslint_d`]: https://www.npmjs.com/package/eslint_d
403[`eslint-loader`]: https://www.npmjs.com/package/eslint-loader
404
405#### `import/internal-regex`
406
407A regex for packages should be treated as internal. Useful when you are utilizing a monorepo setup or developing a set of packages that depend on each other.
408
409By default, any package referenced from [`import/external-module-folders`](#importexternal-module-folders) will be considered as "external", including packages in a monorepo like yarn workspace or lerna emvironentment. If you want to mark these packages as "internal" this will be useful.
410
411For example, if you pacakges in a monorepo are all in `@scope`, you can configure `import/internal-regex` like this
412
413```yaml
414# .eslintrc.yml
415settings:
416 import/internal-regex: ^@scope/
417```
418
419
420## SublimeLinter-eslint
421
422SublimeLinter-eslint introduced a change to support `.eslintignore` files
423which altered the way file paths are passed to ESLint when linting during editing.
424This change sends a relative path instead of the absolute path to the file (as ESLint
425normally provides), which can make it impossible for this plugin to resolve dependencies
426on the filesystem.
427
428This workaround should no longer be necessary with the release of ESLint 2.0, when
429`.eslintignore` will be updated to work more like a `.gitignore`, which should
430support proper ignoring of absolute paths via `--stdin-filename`.
431
432In the meantime, see [roadhump/SublimeLinter-eslint#58](https://github.com/roadhump/SublimeLinter-eslint/issues/58)
433for more details and discussion, but essentially, you may find you need to add the following
434`SublimeLinter` config to your Sublime project file:
435
436```json
437{
438 "folders":
439 [
440 {
441 "path": "code"
442 }
443 ],
444 "SublimeLinter":
445 {
446 "linters":
447 {
448 "eslint":
449 {
450 "chdir": "${project}/code"
451 }
452 }
453 }
454}
455```
456
457Note that `${project}/code` matches the `code` provided at `folders[0].path`.
458
459The purpose of the `chdir` setting, in this case, is to set the working directory
460from which ESLint is executed to be the same as the directory on which SublimeLinter-eslint
461bases the relative path it provides.
462
463See the SublimeLinter docs on [`chdir`](http://www.sublimelinter.com/en/latest/linter_settings.html#chdir)
464for more information, in case this does not work with your project.
465
466If you are not using `.eslintignore`, or don't have a Sublime project file, you can also
467do the following via a `.sublimelinterrc` file in some ancestor directory of your
468code:
469
470```json
471{
472 "linters": {
473 "eslint": {
474 "args": ["--stdin-filename", "@"]
475 }
476 }
477}
478```
479
480I also found that I needed to set `rc_search_limit` to `null`, which removes the file
481hierarchy search limit when looking up the directory tree for `.sublimelinterrc`:
482
483In Package Settings / SublimeLinter / User Settings:
484```json
485{
486 "user": {
487 "rc_search_limit": null
488 }
489}
490```
491
492I believe this defaults to `3`, so you may not need to alter it depending on your
493project folder max depth.