ESLint: How can I restrict certain paths with "no-restricted-imports" but allow subpaths?

Viewed 1358

I am using Material-UI and I am switching all my imports from

import { Button } from "@material-ui/core";

to

import Button from "@material-ui/core/Button";

I wanted to add a lint rule to not allow direct imports from "@material-ui/core", but allow for any subfolders, eg "@material-ui/core/Button".

I found a "no-restricted-imports" rule which is supposed to tackle it, but I can only restrict anything under "@material-ui/core", so "@material-ui/core/*" gets restricted as well.

I tried several ways to set up the rules, but all of them are failing for my use case. Namely:

"no-restricted-imports": ["error", "@material-ui/core"]
///////
"no-restricted-imports": ["error", {
    "patterns": ["@material-ui/core"]
}]

But neither would work. Am I missing something or is it just not possible to achieve?

2 Answers

I wanted to do the same thing with lodash.

For Treeshaking, I wanted to restrict

import {get} from 'lodash';

but allow

import get from 'lodash/get';

eslint config for this,

'no-restricted-imports': [
      'error',
      {
        paths: [
          {
            name: 'lodash',
            message:
              "Please use `import [package] from 'lodash/[package]'` instead."
          }
        ],
        patterns: ['!lodash/*']
      }
    ]

You can try similar for your package.

You can use overrides for some filepaths

"no-restricted-imports": ["error", "@material-ui/core"],
"overrides": [{
  "files": [...],
  "rules: {
    "no-restricted-imports": ["error", {
      "patterns": ["@material-ui/core"]
    }]
  },
}],
Related