Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

eslint-plugin-import-x

Package Overview
Dependencies
Maintainers
1
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

eslint-plugin-import-x

Import with sanity.

  • 4.4.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
521K
increased by6.17%
Maintainers
1
Weekly downloads
 
Created
Source

eslint-plugin-import-x

GitHub Actions Codecov type-coverage npm GitHub Release

Conventional Commits Renovate enabled JavaScript Style Guide Code Style: Prettier

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.

eslint-plugin-i is now eslint-plugin-import-x

IF YOU ARE USING THIS WITH SUBLIME: see the bottom section for important info.

Rules

💼 Configurations enabled in.
⚠️ Configurations set to warn in.
🚫 Configurations disabled in.
❗ Set in the errors configuration.
☑️ Set in the recommended configuration.
⌨️ Set in the typescript configuration.
🚸 Set in the warnings configuration.
🔧 Automatically fixable by the --fix CLI option.
💡 Manually fixable by editor suggestions.
❌ Deprecated.

Helpful warnings

Name                      Description💼⚠️🚫🔧💡
exportForbid any invalid exports, i.e. re-export of the same name.❗ ☑️
no-deprecatedForbid imported names marked with @deprecated documentation tag.
no-empty-named-blocksForbid empty named import blocks.🔧💡
no-extraneous-dependenciesForbid the use of extraneous packages.
no-mutable-exportsForbid the use of mutable exports with var or let.
no-named-as-defaultForbid use of exported name as identifier of default export.☑️ 🚸
no-named-as-default-memberForbid use of exported name as property of default export.☑️ 🚸
no-rename-defaultForbid importing a default export by a different name.🚸
no-unused-modulesForbid modules without exports, or exports without matching import in another module.

Module systems

Name                    Description💼⚠️🚫🔧💡
no-amdForbid AMD require and define calls.
no-commonjsForbid CommonJS require calls and module.exports or exports.*.
no-import-module-exportsForbid import statements with CommonJS module.exports.🔧
no-nodejs-modulesForbid Node.js builtin modules.
unambiguousForbid potentially ambiguous parse goal (script vs. module).

Static analysis

Name                      Description💼⚠️🚫🔧💡
defaultEnsure a default export is present, given a default import.❗ ☑️
namedEnsure named imports correspond to a named export in the remote file.❗ ☑️⌨️
namespaceEnsure imported namespaces contain dereferenced properties as they are dereferenced.❗ ☑️
no-absolute-pathForbid import of modules using absolute paths.🔧
no-cycleForbid a module from importing a module with a dependency path back to itself.
no-dynamic-requireForbid require() calls with expressions.
no-internal-modulesForbid importing the submodules of other modules.
no-relative-packagesForbid importing packages through relative paths.🔧
no-relative-parent-importsForbid importing modules from parent directories.
no-restricted-pathsEnforce which files can be imported in a given folder.
no-self-importForbid a module from importing itself.
no-unresolvedEnsure imports point to a file/module that can be resolved.❗ ☑️
no-useless-path-segmentsForbid unnecessary path segments in import and require statements.🔧
no-webpack-loader-syntaxForbid webpack loader syntax in imports.

Style guide

Name                           Description💼⚠️🚫🔧💡
consistent-type-specifier-styleEnforce or ban the use of inline type-only markers for named imports.🔧
dynamic-import-chunknameEnforce a leading comment with the webpackChunkName for dynamic imports.💡
exports-lastEnsure all exports appear after other statements.
extensionsEnsure consistent use of file extension within the import path.
firstEnsure all imports appear before other statements.🔧
group-exportsPrefer named exports to be grouped together in a single export declaration.
imports-firstReplaced by import-x/first.🔧
max-dependenciesEnforce the maximum number of dependencies a module can have.
newline-after-importEnforce a newline after import statements.🔧
no-anonymous-default-exportForbid anonymous values as default exports.
no-default-exportForbid default exports.
no-duplicatesForbid repeated import of the same module in multiple places.☑️ 🚸🔧
no-named-defaultForbid named default exports.
no-named-exportForbid named exports.
no-namespaceForbid namespace (a.k.a. "wildcard" *) imports.🔧
no-unassigned-importForbid unassigned imports.
orderEnforce a convention in module import order.🔧
prefer-default-exportPrefer a default export if module exports a single name or multiple names.

Installation

# inside your project's working tree
npm install eslint-plugin-import-x --save-dev

Configuration (legacy: .eslintrc*)

[!TIP] If your eslint is >=8.23.0, you're 100% ready to use the new config system. See dedicated section below.

[!NOTE] All rules are off by default. However, you may configure them manually in your .eslintrc.(yml|json|js), or extend one of the canned configs:

---
extends:
  - eslint:recommended
  - plugin:import-x/recommended
  # alternatively, 'recommended' is the combination of these two rule sets:
  - plugin:import-x/errors
  - plugin:import-x/warnings

# or configure manually:
plugins:
  - import-x

rules:
  import-x/no-unresolved: [2, { commonjs: true, amd: true }]
  import-x/named: 2
  import-x/namespace: 2
  import-x/default: 2
  import-x/export: 2
  # etc...

TypeScript

You may use the following snippet or assemble your own config using the granular settings described below it.

[!WARNING] Make sure you have installed @typescript-eslint/parser and eslint-import-resolver-typescript which are used in the following configuration.

extends:
  - eslint:recommended
  - plugin:import-x/recommended
  # the following lines do the trick
  - plugin:import-x/typescript
settings:
  import-x/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

Configuration (new: eslint.config.js)

From v8.21.0, ESLint announced a new config system. In the new system, .eslintrc* is no longer used. eslint.config.js would be the default config file name.

JS example
import js from '@eslint/js'
import eslintPluginImportX from 'eslint-plugin-import-x'

export default [
  js.configs.recommended,
  eslintPluginImportX.flatConfigs.recommended,
]
Typescript example

You have to install eslint-import-resolver-typescript:

npm install eslint-import-resolver-typescript --save-dev
import js from '@eslint/js'
import eslintPluginImportX from 'eslint-plugin-import-x'
import tsParser from '@typescript-eslint/parser'

export default [
  js.configs.recommended,
  eslintPluginImportX.flatConfigs.recommended,
  eslintPluginImportX.flatConfigs.typescript,
  {
    files: ['**/*.{js,mjs,cjs,jsx,mjsx,ts,tsx,mtsx}'],
    ignores: ['eslint.config.js'],
    languageOptions: {
      parser: tsParser,
      ecmaVersion: 'latest',
      sourceType: 'module',
    },
    rules: {
      'no-unused-vars': 'off',
      'import-x/no-dynamic-require': 'warn',
      'import-x/no-nodejs-modules': 'warn',
    },
  },
]

[!NOTE] A complete list of available configuration can be found in config/flat folders

Resolvers

With the advent of module bundlers and the current state of modules and module syntax specs, it's not always obvious where import x from 'module' should look to find the file behind module.

Up through v0.10ish, this plugin has directly used substack's resolve 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 that Node does not, such as loaders (import 'file!./whatever') and a number of aliasing schemes, such as externals: mapping a module id to a global name at runtime (allowing some modules to be included more traditionally via script tags).

In the interest of supporting both of these, v0.11 introduces resolvers.

Currently Node and webpack resolution have been implemented, but the resolvers are just npm packages, so third party packages are supported (and encouraged!).

You can reference resolvers in several ways (in order of precedence):

  • as a conventional eslint-import-resolver name, like eslint-import-resolver-foo:
# .eslintrc.yml
settings:
  # uses 'eslint-import-resolver-foo':
  import-x/resolver: foo
// .eslintrc.js
module.exports = {
  settings: {
    'import-x/resolver': {
      foo: { someConfig: value },
    },
  },
}
  • with a full npm module name, like my-awesome-npm-module:
# .eslintrc.yml
settings:
  import-x/resolver: 'my-awesome-npm-module'
// .eslintrc.js
module.exports = {
  settings: {
    'import-x/resolver': {
      'my-awesome-npm-module': { someConfig: value },
    },
  },
}
  • with a filesystem path to resolver, defined in this example as a computed property name:
// .eslintrc.js
module.exports = {
  settings: {
    'import-x/resolver': {
      [path.resolve('../../../my-resolver')]: { someConfig: value },
    },
  },
}
  • use the import or require syntax to directly import the resolver object:
// .eslintrc.mjs
import tsResolver from 'eslint-import-resolver-typescript'

export default {
  settings: {
    'import-x/resolver': {
      name: 'tsResolver', // required, could be any string you like
      // enable: false, // optional, defaults to true
      options: { someConfig: value }, // optional, options to pass to the resolver
      resolver: tsResolver, // required, the resolver object
    },
  },
}
// .eslintrc.cjs
const tsResolver = require('eslint-import-resolver-typescript')

module.exports = {
  settings: {
    'import-x/resolver': {
      name: 'tsResolver', // required, could be any string you like
      // enable: false, // optional, defaults to true
      options: { someConfig: value }, // optional, options to pass to the resolver
      resolver: tsResolver, // required, the resolver object
    },
  },
}

Relative paths will be resolved relative to the source's nearest package.json or the process's current working directory if no package.json is found.

If you are interesting in writing a resolver, see the spec for more details.

Settings

You may set the following settings in your .eslintrc:

import-x/extensions

A list of file extensions that will be parsed as modules and inspected for exports.

This defaults to ['.js'], unless you are using the react shared config, in which case it is specified as ['.js', '.jsx']. Despite the default, if you are using TypeScript (without the plugin:import-x/typescript config described above) you must specify the new extensions (.ts, and also .tsx if using React).

"settings": {
  "import-x/extensions": [
    ".js",
    ".jsx"
  ]
}

If you require more granular extension definitions, you can use:

"settings": {
  "import-x/resolver": {
    "node": {
      "extensions": [
        ".js",
        ".jsx"
      ]
    }
  }
}

Note that this is different from (and likely a subset of) any import-x/resolver extensions settings, which may include .json, .coffee, etc. which will still factor into the no-unresolved rule.

Also, the following import-x/ignore patterns will overrule this list.

import-x/ignore

A list of regex strings that, if matched by a path, will not report the matching module if no exports are found. In practice, this means rules other than no-unresolved will not report on any imports with (absolute filesystem) paths matching this pattern.

no-unresolved has its own ignore setting.

settings:
  import-x/ignore:
    - \.coffee$ # fraught with parse errors
    - \.(scss|less|css)$ # can't parse unprocessed CSS modules, either

import-x/core-modules

An array of additional modules to consider as "core" modules--modules that should be considered resolved but have no path on the filesystem. Your resolver may already define some of these (for example, the Node resolver knows about fs and path), so you need not redefine those.

For example, Electron exposes an electron module:

import 'electron' // without extra config, will be flagged as unresolved!

that would otherwise be unresolved. To avoid this, you may provide electron as a core module:

# .eslintrc.yml
settings:
  import-x/core-modules: [electron]

In Electron's specific case, there is a shared config named electron that specifies this for you.

Contribution of more such shared configs for other platforms are welcome!

import-x/external-module-folders

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 example bower_components or jspm_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 using yarn PnP as your package manager, add the .yarn folder and all your installed dependencies will be considered as external, instead of internal.

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 named jspm_modules or which has a direct or non-direct parent named jspm_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 so components won't match bower_components and packages/ui won't match packages/ui-utils (but will match packages/ui/utils).

import-x/parsers

A map from parsers to file extension arrays. If a file extension is matched, the dependency parser will require and use the map key as the parser instead of the configured ESLint parser. This is useful if you're inter-op-ing with TypeScript directly using webpack, for example:

# .eslintrc.yml
settings:
  import-x/parsers:
    '@typescript-eslint/parser': [.ts, .tsx]

In this case, @typescript-eslint/parser must be installed and require-able from the running eslint 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 moderately ESTree-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 strange behavior beyond here, but steel your heart against the likely outcome of closing with wontfix.

import-x/resolver

See resolvers.

import-x/cache

Settings 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.

For 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)

For long-lasting processes, like eslint_d or eslint-loader, however, it's important that there be some notion of staleness.

If you never use eslint_d or eslint-loader, you may set the cache lifetime to Infinity and everything should be fine:

# .eslintrc.yml
settings:
  import-x/cache:
    lifetime:  # or Infinity

Otherwise, set some integer, and cache entries will be evicted after that many seconds have elapsed:

# .eslintrc.yml
settings:
  import-x/cache:
    lifetime: 5 # 30 is the default

import-x/internal-regex

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 from import-x/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 configure import-x/internal-regex like this

# .eslintrc.yml
settings:
  import-x/internal-regex: ^@scope/

SublimeLinter-eslint

SublimeLinter-eslint introduced a change to support .eslintignore files which 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 ESLint normally provides), which can make it impossible for this plugin to resolve dependencies on 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 should support proper ignoring of absolute paths via --stdin-filename.

In the meantime, see roadhump/SublimeLinter-eslint#58 for more details and discussion, but essentially, you may find you need to add the following SublimeLinter config to your Sublime project file:

{
  "folders": [
    {
      "path": "code"
    }
  ],
  "SublimeLinter": {
    "linters": {
      "eslint": {
        "chdir": "${project}/code"
      }
    }
  }
}

Note that ${project}/code matches the code provided at folders[0].path.

The purpose of the chdir setting, in this case, is to set the working directory from which ESLint is executed to be the same as the directory on which SublimeLinter-eslint bases the relative path it provides.

See the SublimeLinter docs on chdir 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 also do the following via a .sublimelinterrc file in some ancestor directory of your code:

{
  "linters": {
    "eslint": {
      "args": ["--stdin-filename", "@"]
    }
  }
}

I also found that I needed to set rc_search_limit to null, which removes the file hierarchy 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 to 3, so you may not need to alter it depending on your project folder max depth.

Keywords

FAQs

Package last updated on 30 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc