Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to forbid import from path in eslint except one permitted includer?

Tags:

eslint

linter

Can i write rule that will raise an error if one or more files are importing from one path, but permit import these files for file.js?

like image 725
IC_ Avatar asked Sep 15 '25 13:09

IC_


2 Answers

You can achieve this with the eslint rule no-restricted-imports: https://eslint.org/docs/rules/no-restricted-imports

In my case, I didn't want to allow my React components to access a 3rd party directly, but use a custom hook instead. The following rule configuration did the job:

"no-restricted-imports": ["error", {
            "patterns": [
                {
                    "group": ["@third/party"],
                    "message": "Please use the custom hook `useThirdParty` instead"
                }
            ]
        }]

Then in the one place where I actually want to allow this, I added the following comment:

// eslint-disable-next-line no-restricted-imports
import * as ThirdParty from '@third/party';

In order to disable the rule just for this particular line

like image 79
amit Avatar answered Sep 17 '25 02:09

amit


What you can do is add a rule that restricts the import

'no-restricted-imports': [
  'error',
  {
    patterns: [
      {
        group: ['@third/party'],
        message:
          'Importing from @third/party is only supported in *.thirdParty.ts files',
      },
    ],
  },
],

And then you combine that with an override

{
  files: ['src/**/*.thirdParty.ts'],
  rules: { 'no-restricted-imports': 'off' },
},
like image 21
Tobbe Avatar answered Sep 17 '25 03:09

Tobbe