Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork1.6k
ESLint plugin with rules that help validate proper imports.
License
import-js/eslint-plugin-import
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This 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.
IF YOU ARE USING THIS WITH SUBLIME: see thebottom section for important info.
💼 Configurations enabled in.
🚫 Configurations disabled in.
❗ Set in theerrors
configuration.
☑️ Set in therecommended
configuration.
⌨️ Set in thetypescript
configuration.
🚸 Set in thewarnings
configuration.
🔧 Automatically fixable by the--fix
CLI option.
💡 Manually fixable byeditor suggestions.
❌ Deprecated.
Name | Description | 💼 | 🚫 | 🔧 | 💡 | ❌ | |
---|---|---|---|---|---|---|---|
export | Forbid any invalid exports, i.e. re-export of the same name. | ❗ ☑️ | |||||
no-deprecated | Forbid imported names marked with@deprecated documentation tag. | ||||||
no-empty-named-blocks | Forbid empty named import blocks. | 🔧 | 💡 | ||||
no-extraneous-dependencies | Forbid the use of extraneous packages. | ||||||
no-mutable-exports | Forbid the use of mutable exports withvar orlet . | ||||||
no-named-as-default | Forbid use of exported name as identifier of default export. | ☑️ 🚸 | |||||
no-named-as-default-member | Forbid use of exported name as property of default export. | ☑️ 🚸 | |||||
no-unused-modules | Forbid modules without exports, or exports without matching import in another module. |
Name | Description | 💼 | 🚫 | 🔧 | 💡 | ❌ | |
---|---|---|---|---|---|---|---|
no-amd | Forbid AMDrequire anddefine calls. | ||||||
no-commonjs | Forbid CommonJSrequire calls andmodule.exports orexports.* . | ||||||
no-import-module-exports | Forbid import statements with CommonJS module.exports. | 🔧 | |||||
no-nodejs-modules | Forbid Node.js builtin modules. | ||||||
unambiguous | Forbid potentially ambiguous parse goal (script vs.module ). |
Name | Description | 💼 | 🚫 | 🔧 | 💡 | ❌ | |
---|---|---|---|---|---|---|---|
default | Ensure a default export is present, given a default import. | ❗ ☑️ | |||||
enforce-node-protocol-usage | Enforce either using, or omitting, thenode: protocol when importing Node.js builtin modules. | 🔧 | |||||
named | Ensure named imports correspond to a named export in the remote file. | ❗ ☑️ | ⌨️ | ||||
namespace | Ensure imported namespaces contain dereferenced properties as they are dereferenced. | ❗ ☑️ | |||||
no-absolute-path | Forbid import of modules using absolute paths. | 🔧 | |||||
no-cycle | Forbid a module from importing a module with a dependency path back to itself. | ||||||
no-dynamic-require | Forbidrequire() calls with expressions. | ||||||
no-internal-modules | Forbid importing the submodules of other modules. | ||||||
no-relative-packages | Forbid importing packages through relative paths. | 🔧 | |||||
no-relative-parent-imports | Forbid importing modules from parent directories. | ||||||
no-restricted-paths | Enforce which files can be imported in a given folder. | ||||||
no-self-import | Forbid a module from importing itself. | ||||||
no-unresolved | Ensure imports point to a file/module that can be resolved. | ❗ ☑️ | |||||
no-useless-path-segments | Forbid unnecessary path segments in import and require statements. | 🔧 | |||||
no-webpack-loader-syntax | Forbid webpack loader syntax in imports. |
Name | Description | 💼 | 🚫 | 🔧 | 💡 | ❌ | |
---|---|---|---|---|---|---|---|
consistent-type-specifier-style | Enforce or ban the use of inline type-only markers for named imports. | 🔧 | |||||
dynamic-import-chunkname | Enforce a leading comment with the webpackChunkName for dynamic imports. | 💡 | |||||
exports-last | Ensure all exports appear after other statements. | ||||||
extensions | Ensure consistent use of file extension within the import path. | ||||||
first | Ensure all imports appear before other statements. | 🔧 | |||||
group-exports | Prefer named exports to be grouped together in a single export declaration | ||||||
imports-first | Replaced byimport/first . | 🔧 | ❌ | ||||
max-dependencies | Enforce the maximum number of dependencies a module can have. | ||||||
newline-after-import | Enforce a newline after import statements. | 🔧 | |||||
no-anonymous-default-export | Forbid anonymous values as default exports. | ||||||
no-default-export | Forbid default exports. | ||||||
no-duplicates | Forbid repeated import of the same module in multiple places. | ☑️ 🚸 | 🔧 | ||||
no-named-default | Forbid named default exports. | ||||||
no-named-export | Forbid named exports. | ||||||
no-namespace | Forbid namespace (a.k.a. "wildcard"* ) imports. | 🔧 | |||||
no-unassigned-import | Forbid unassigned imports | ||||||
order | Enforce a convention in module import order. | 🔧 | |||||
prefer-default-export | Prefer a default export if module exports a single name or multiple names. |
Available as part of the Tidelift Subscription.
The maintainers ofeslint-plugin-import
and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use.Learn more.
# inside your project's working treenpm install eslint-plugin-import --save-dev
All rules are off by default. However, you may extend one of the preset configs, or configure them manually in your.eslintrc.(yml|json|js)
.
- Extending a preset config:
{"extends": ["eslint:recommended","plugin:import/recommended", ],}
- Configuring manually:
{"rules": {"import/no-unresolved": ["error", {"commonjs":true,"amd":true }],"import/named":"error","import/namespace":"error","import/default":"error","import/export":"error",// etc... },},
All rules are off by default. However, you may configure them manually in youreslint.config.(js|cjs|mjs)
, or extend one of the preset configs:
importimportPluginfrom'eslint-plugin-import';importjsfrom'@eslint/js';exportdefault[js.configs.recommended,importPlugin.flatConfigs.recommended,{files:['**/*.{js,mjs,cjs}'],languageOptions:{ecmaVersion:'latest',sourceType:'module',},rules:{'no-unused-vars':'off','import/no-dynamic-require':'warn','import/no-nodejs-modules':'warn',},},];
You may use the following snippet or assemble your own config using the granular settings described below it.
Make sure you have installed@typescript-eslint/parser
andeslint-import-resolver-typescript
which are used in the following configuration.
{"extends": ["eslint:recommended","plugin:import/recommended",// the following lines do the trick"plugin:import/typescript", ],"settings": {"import/resolver": {// You will also need to install and configure the TypeScript resolver// See also https://github.com/import-js/eslint-import-resolver-typescript#configuration"typescript":true,"node":true, }, },}
If you are using theconfig
method fromtypescript-eslint
, ensure that theflatConfig
is included within theextends
array.
importtseslintfrom'typescript-eslint';importimportPluginfrom'eslint-plugin-import';importjsfrom'@eslint/js';exportdefaulttseslint.config(js.configs.recommended,// other configs...{files:['**/*.{ts,tsx}'],extends:[importPlugin.flatConfigs.recommended,importPlugin.flatConfigs.typescript],// other configs...});
With the advent of module bundlers and the current state of modules and modulesyntax specs, it's not always obvious whereimport x from 'module'
should lookto find the file behindmodule
.
Up through v0.10ish, this plugin has directly used substack'sresolve
plugin,which implements Node's import behavior. This works pretty well in most cases.
However, webpack allows a number of things in import module source strings thatNode does not, such as loaders (import 'file!./whatever'
) and a number ofaliasing schemes, such asexternals
: mapping a module id to a global name atruntime (allowing some modules to be included more traditionally via script tags).
In the interest of supporting both of these, v0.11 introduces resolvers.
CurrentlyNode andwebpack resolution have been implemented, but theresolvers are just npm packages, sothird party packages are supported (and encouraged!).
You can reference resolvers in several ways (in order of precedence):
- as a conventional
eslint-import-resolver
name, likeeslint-import-resolver-foo
:
// .eslintrc{"settings": {// uses 'eslint-import-resolver-foo':"import/resolver":"foo", },}
# .eslintrc.ymlsettings:# uses 'eslint-import-resolver-foo':import/resolver:foo
// .eslintrc.jsmodule.exports={settings:{'import/resolver':{foo:{someConfig:value}}}}
- with a full npm module name, like
my-awesome-npm-module
:
// .eslintrc{"settings": {"import/resolver":"my-awesome-npm-module", },}
# .eslintrc.ymlsettings:import/resolver:'my-awesome-npm-module'
// .eslintrc.jsmodule.exports={settings:{'import/resolver':{'my-awesome-npm-module':{someConfig:value}}}}
- with a filesystem path to resolver, defined in this example as a
computed property
name:
// .eslintrc.jsmodule.exports={settings:{'import/resolver':{[path.resolve('../../../my-resolver')]:{someConfig:value}}}}
Relative paths will be resolved relative to the source's nearestpackage.json
orthe process's current working directory if nopackage.json
is found.
If you are interesting in writing a resolver, see thespec for more details.
You may set the following settings in your.eslintrc
:
A list of file extensions that will be parsed as modules and inspected forexport
s.
This defaults to['.js']
, unless you are using thereact
shared config,in which case it is specified as['.js', '.jsx']
. Despite the default,if you are using TypeScript (without theplugin:import/typescript
configdescribed above) you must specify the new extensions (.ts
, and also.tsx
if using React).
"settings":{"import/extensions":[".js",".jsx"]}
If you require more granular extension definitions, you can use:
"settings":{"import/resolver":{"node":{"extensions":[".js",".jsx"]}}}
Note that this is different from (and likely a subset of) anyimport/resolver
extensions settings, which may include.json
,.coffee
, etc. which will stillfactor into theno-unresolved
rule.
Also, the followingimport/ignore
patterns will overrule this list.
A list of regex strings that, if matched by a path, willnot report the matching module if noexport
s are found.In practice, this means rules other thanno-unresolved
will not report on anyimport
s with (absolute filesystem) paths matching this pattern.
no-unresolved
has its ownignore
setting.
{"settings": {"import/ignore": ["\.coffee$",// fraught with parse errors"\.(scss|less|css)$",// can't parse unprocessed CSS modules, either ], },}
An array of additional modules to consider as "core" modules--modules that shouldbe considered resolved but have no path on the filesystem. Your resolver mayalready define some of these (for example, the Node resolver knows aboutfs
andpath
), so you need not redefine those.
For example, Electron exposes anelectron
module:
import'electron'// without extra config, will be flagged as unresolved!
that would otherwise be unresolved. To avoid this, you may provideelectron
as acore module:
// .eslintrc{"settings": {"import/core-modules": ["electron"], },}
In Electron's specific case, there is a shared config namedelectron
that specifies this for you.
Contribution of more such shared configs for other platforms are welcome!
An 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 consider modules from some folders, for examplebower_components
orjspm_modules
, as "external".
This option is also useful in a monorepo setup: list here all directories that contain monorepo's packages and they will be treated as external ones no matter which resolver is used.
If you are usingyarn
PnP as your package manager, add the.yarn
folder and all your installed dependencies will be considered asexternal
, instead ofinternal
.
Each item in this array is either a folder's name, its subpath, or its absolute prefix path:
jspm_modules
will match any file or folder namedjspm_modules
or which has a direct or non-direct parent namedjspm_modules
, e.g./home/me/project/jspm_modules
or/home/me/project/jspm_modules/some-pkg/index.js
.packages/core
will match any path that contains these two segments, for example/home/me/project/packages/core/src/utils.js
./home/me/project/packages
will only match files and directories inside this directory, and the directory itself.
Please note that incomplete names are not allowed here socomponents
won't matchbower_components
andpackages/ui
won't matchpackages/ui-utils
(but will matchpackages/ui/utils
).
A map from parsers to file extension arrays. If a file extension is matched, thedependency parser will require and use the map key as the parser instead of theconfigured ESLint parser. This is useful if you're inter-op-ing with TypeScriptdirectly using webpack, for example:
// .eslintrc{"settings": {"import/parsers": {"@typescript-eslint/parser": [".ts",".tsx"], }, },}
In this case,@typescript-eslint/parser
must be installed and require-able from the runningeslint
module's location(i.e., install it as a peer of ESLint).
This is currently only tested with@typescript-eslint/parser
(and its predecessor,typescript-eslint-parser
) but should theoretically work with any moderatelyESTree-compliant parser.
It's difficult to say how well various plugin features will be supported, too,depending on how far down the rabbit hole goes. Submit an issue if you find strangebehavior beyond here, but steel your heart against the likely outcome of closingwithwontfix
.
Seeresolvers.
Settings for cache behavior. Memoization is used at various levels to avoid the copious amount offs.statSync
/module parse calls required to correctly report errors.
For normaleslint
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)
For long-lasting processes, likeeslint_d
oreslint-loader
, however, it's important that there be some notion of staleness.
If you never useeslint_d
oreslint-loader
, you may set the cache lifetime toInfinity
and everything should be fine:
// .eslintrc{"settings": {"import/cache": {"lifetime":"∞",// or Infinity, in a JS config }, },}
Otherwise, set some integer, and cache entries will be evicted after that many seconds have elapsed:
// .eslintrc{"settings": {"import/cache": {"lifetime":5,// 30 is the default }, },}
A 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.
By default, any package referenced fromimport/external-module-folders
will be considered as "external", including packages in a monorepo like yarn workspace or lerna environment. If you want to mark these packages as "internal" this will be useful.
For example, if your packages in a monorepo are all in@scope
, you can configureimport/internal-regex
like this
// .eslintrc{"settings": {"import/internal-regex":"^@scope/", },}
A string that represents the version of Node.js that you are using.A falsy value will imply the version of Node.js that you are running ESLint with.
// .eslintrc{"settings": {"import/node-version":"22.3.4", },}
SublimeLinter-eslint introduced a change to support.eslintignore
fileswhich altered the way file paths are passed to ESLint when linting during editing.This change sends a relative path instead of the absolute path to the file (as ESLintnormally provides), which can make it impossible for this plugin to resolve dependencieson the filesystem.
This workaround should no longer be necessary with the release of ESLint 2.0, when.eslintignore
will be updated to work more like a.gitignore
, which shouldsupport proper ignoring of absolute paths via--stdin-filename
.
In the meantime, seeroadhump/SublimeLinter-eslint#58for more details and discussion, but essentially, you may find you need to add the followingSublimeLinter
config to your Sublime project file:
{"folders": [ {"path":"code" } ],"SublimeLinter": {"linters": {"eslint": {"chdir":"${project}/code" } } }}
Note that${project}/code
matches thecode
provided atfolders[0].path
.
The purpose of thechdir
setting, in this case, is to set the working directoryfrom which ESLint is executed to be the same as the directory on which SublimeLinter-eslintbases the relative path it provides.
See the SublimeLinter docs onchdir
for more information, in case this does not work with your project.
If you are not using.eslintignore
, or don't have a Sublime project file, you can alsodo the following via a.sublimelinterrc
file in some ancestor directory of yourcode:
{"linters": {"eslint": {"args": ["--stdin-filename","@"] } }}
I also found that I needed to setrc_search_limit
tonull
, which removes the filehierarchy search limit when looking up the directory tree for.sublimelinterrc
:
In Package Settings / SublimeLinter / User Settings:
{"user": {"rc_search_limit":null }}
I believe this defaults to3
, so you may not need to alter it depending on yourproject folder max depth.
About
ESLint plugin with rules that help validate proper imports.
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.