首页 > 解决方案 > ESLint:如何使用“no-restricted-imports”限制某些路径但允许子路径?

问题描述

我正在使用 Material-UI,我正在切换我的所有导入

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

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

我想添加一个 lint 规则,不允许从“@material-ui/core”直接导入,但允许任何子文件夹,例如“@material-ui/core/Button”。

我找到了一个应该解决它的“无限制导入”规则,但我只能限制“@material-ui/core”下的任何内容,因此“@material-ui/core/*”也受到限制。

我尝试了几种设置规则的方法,但对于我的用例来说,所有这些方法都失败了。即:

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

但两者都行不通。我错过了什么还是无法实现?

标签: javascripteslintlint

解决方案


我想用 lodash 做同样的事情。

对于 Treeshaking,我想限制

从'lodash'导入{get};

但允许

从“lodash/get”导入获取;

为此的 eslint 配置,

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

您可以为您的包裹尝试类似的方法。


推荐阅读