eslint no-restricted-imports - 防止从以模式结尾的路径导入

dwj*_*ton 6 glob gitignore eslint

根据eslint no-restricted-imports 文档

使用对象形式时,您还可以指定gitignore 样式模式数组 :

"no-restricted-imports": ["error", {
    "paths": ["import1", "import2"],
    "patterns": ["import1/private/*", "import2/*", "!import2/good"] }]
Run Code Online (Sandbox Code Playgroud)

(强调我的)

我想要做的是限制从父索引文件导入 - 因为这会导致循环依赖问题(我也在使用该import/no-cycle规则,但也显式使用该规则是有意义的。)

也就是说,我想禁止进口,如:

import foo from "../.."; 
import bar from "../../.."; 
Run Code Online (Sandbox Code Playgroud)

我还想禁止进口,如:

import a from "../Components"; 
Run Code Online (Sandbox Code Playgroud)

但不喜欢

import  b from "../Components/Foo"; 
Run Code Online (Sandbox Code Playgroud)

我曾尝试使用此规则:

'no-restricted-imports': [
  'error', 
  {
    patterns: [
      '**/..', 
      '**/Components'
    ]
  }, 
Run Code Online (Sandbox Code Playgroud)

但这会导致导入错误:

import  b from "../Components/Foo"; 
Run Code Online (Sandbox Code Playgroud)

有没有办法在 gitignore 样式模式中指定“字符串结尾”?

Von*_*onC 9

首先,确保您没有 set import/no-relative-parent-imports,否则任何../导入都会失败。

其次,如果这确实遵循.gitignore规则,则您不能为文件夹制定规则(例如**/..**/Components)。
因为,一旦您忽略某个文件夹,该文件夹元素的任何其他规则都将被忽略。

尝试:

'no-restricted-imports': [
  'error', 
  {
    patterns: [
      '**/../*', 
      '!**/../Components', 
      '**/../Components/*', 
      '!**/../Components/Foo', 
    ]
  }, 
Run Code Online (Sandbox Code Playgroud)