eslint no-restricted-imports - prevent an import from from path ending with pattern

Viewed 7058

According to the eslint no-restricted-imports documentation

When using the object form, you can also specify an array of gitignore-style patterns:

"no-restricted-imports": ["error", {
    "paths": ["import1", "import2"],
    "patterns": ["import1/private/*", "import2/*", "!import2/good"] }]

(Emphasis mine)

What I'm trying to do is restrict imports from parent index files - as this is causing issues with cyclical dependencies (I am also using the import/no-cycle rule, but it makes sense to also explicitly use this rule.)

That is, I want to ban imports like:

import foo from "../.."; 
import bar from "../../.."; 

I also want to ban imports like:

import a from "../Components"; 

but not like

import  b from "../Components/Foo"; 

I have tried using this rule:

'no-restricted-imports': [
  'error', 
  {
    patterns: [
      '**/..', 
      '**/Components'
    ]
  }, 

But this causes on errors on imports of:

import  b from "../Components/Foo"; 

Is there a way to specify 'end of string' in a gitignore style pattern?

1 Answers

First, make sure you don't have set import/no-relative-parent-imports, or any ../ import would fail.

Second, if this really follows .gitignore rules, you cannot have rules for folders (like **/.. or **/Components).
Because, once you ignore a folder, any other rule for elements inside that folder would be ignored.

Try:

'no-restricted-imports': [
  'error', 
  {
    patterns: [
      '**/../*', 
      '!**/../Components', 
      '**/../Components/*', 
      '!**/../Components/Foo', 
    ]
  }, 
Related