首页 > 解决方案 > 如何使用 ESLint 通过特定文件夹的绝对路径限制模块的导入

问题描述

我有文件夹结构:

my_project
 |------ modules.private
 |        |------ broker_module
 |                 |------ BrokerModule.js
 |
 |------ src
 |        |------ AppService
 |                 |------ AppService.js
 |        
 |        |------ Components
 |                 |------ ScreenLogin.js
 | 
   

我需要限制所有区域从 modules.private 的绝对导入,除了“./src/AppService”。

案例没有错误。Linted 文件是 './src/AppService/AppService.js':

// NO ERROR
import { BrokerModule } from 'broker_module';

有错误的情况。Linted 文件是 './src/componets/ScreenLogin.js':

// Error: can not import broker_module to restricted zone
import { BrokerModule } from 'broker_module';

我已经尝试过https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-restricted-paths.md,并制定了这样的规则:

// the rule is interpreted like you can not import to target zone './src/components' from 'from': 'broker_module'

'rules': {
    'import/no-restricted-paths': [
      'error',
      {
        'zones': [
          { 'target': './src/components', 'from': 'broker_module' },
        ],
      }
    ],
  },

但它不适用于绝对路径。而且我尝试了这个 ESLint 规则https://eslint.org/docs/rules/no-restricted-imports

'no-restricted-imports': ["error", {
    "paths": ["broker_module"],
}]

它有效,但适用于所有区域。这意味着在我从 broker_module 导入实体的所有地方都会出现错误。你能告诉我如何使用 eslint-plugin-import/no-restricted-paths 写入绝对路径的受限区域,或者使用 ESLint/no-restricted-imports 来限制仅导入对于特定区域,而不是所有文件夹。

标签: javascriptimporteslintabsolute-patheslintrc

解决方案


我已经找到了如何限制特定区域的决定。可以通过两种方式实现:

  1. 在您的 .eslintrc.js 文件中写入全局模式并覆盖:
'rules': {
    'no-restricted-imports': ['error', {
      'paths': ['vtb.broker2.api.0'],
    }],
    'import/no-restricted-paths': [
      'error',
      {
        'zones': [
          { 'target': './src/vtb', 'from': './src/vtb/api.1' },
        ],
      }
    ],
  },
  'overrides': [
    {
      'files': ['./src/vtb/api.1/*.ts', './src/vtb/api.1/**/*.ts'],
      'rules': {
        'no-restricted-imports': 'off',
      },
    }
  ],

2.根据官方文档https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy可以覆盖规则只是在要更改的文件夹目录的父级中创建规则创建一个文件 .eslintrc.js ,该文件仅适用于该文件夹,例如关闭规则:

  'import/no-restricted-paths': [
      'off',
  },

推荐阅读