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
?
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
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' },
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With