2

E.g. I want to restrict importing react-use, but allow react-use/lib/usePrevious. I tried:

  rules: {
    'no-restricted-imports': [2, { patterns: [
      'react-use',
    ] }],
  },

And

  rules: {
    'no-restricted-imports': [2, { patterns: [
      'react-use',
      '!react-use/*',
    ] }],
  },

However, in both case, I get an error for:

import usePrevious from 'react-use/lib/usePrevious';

I only want an error for:

import something from 'react-use';
Adam
  • 3,829
  • 1
  • 21
  • 31
Leo Jiang
  • 24,497
  • 49
  • 154
  • 284

2 Answers2

2

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 the same for your package.

Khushbu Patel
  • 193
  • 13
1

This is a limitation with the ignore library that ESLint uses to check each pattern. It was built to replace existing file ignore methods with something more compact and barebones.

Specifically, the problem seems to be that this ignore system assumes your file structure is strictly directory-like, where restricting react-use and ignoring !react-use/* implies that react-use is a folder. However, with a module import structure, react-use can refer to a file (via its index.js) and simultaneously contain subfolders like react-use/lib making it usable as both a file and a folder.

So it won't be possible to ignore the base of the module while restricting a subpath.

Adam
  • 3,829
  • 1
  • 21
  • 31