How to restrict the import of the module by absolute path for the particular folder with ESLint

8.6k views Asked by At

I have the folder structure:

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

And I need to restrict the absolute import from modules.private for all zones, except './src/AppService'.

Case no error. Linted file is './src/AppService/AppService.js':

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

Case with error. Linted file is './src/componets/ScreenLogin.js':

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

I already tried https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-restricted-paths.md, and made the rule like this:

// 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' },
        ],
      }
    ],
  },

But it is not working with absolute path. And more over I tried this ESLint rule https://eslint.org/docs/rules/no-restricted-imports:

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

And it works, but for all zones. It means get the error in all places where I import entities from broker_module. Can you tell me please how it possible in case to use eslint-plugin-import/no-restricted-paths to write to restricted zone for absolute path, or maybe in case to use ESLint/no-restricted-imports to restrict the import only for the particular zone, not for the all folders.

1

There are 1 answers

0
jocoders On

I have found the decision how to restrict the particular zone. It could be achieved with two ways:

  1. Write global pattern in your .eslintrc.js file with overrides:
'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.According the official docs https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy possible to overrides the rule just to create in the parent of the folder directory where you want to change the rule make a file .eslintrc.js that will work only for this folder and for example to off the rule:

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