简体   繁体   中英

Eslint no-restricted-imports only restrict importing from a package root?

Eg 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';

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM