Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 655
dwjohnston Avatar asked Nov 24 '20 22:11

dwjohnston


People also ask

How do I turn off ESLint rule?

If you want to disable an ESLint rule in a file or on a specific line, you can add a comment. On a single line: const message = 'foo'; console. log(message); // eslint-disable-line no-console // eslint-disable-next-line no-console console.

How do you bypass ESLint?

To temporarily turn off ESLint, you should add a block comment /* eslint-disable */ before the lines that you're interested in: /* eslint-disable */ console.

What is 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 for customization options for the resolution (i.e. additional filetypes, NODE_PATH , etc.)


Video Answer


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', 
    ]
  }, 
like image 115
VonC Avatar answered Oct 19 '22 07:10

VonC