【问题标题】:ESLint: How can I restrict certain paths with "no-restricted-imports" but allow subpaths?ESLint:如何使用“no-restricted-imports”限制某些路径但允许子路径?
【发布时间】:2023-03-12 00:39:02
【问题描述】:

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

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

到

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

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

我发现了一个“no-restricted-imports”规则应该可以解决它,但我只能限制“@material-ui/core”下的任何东西,所以“@material-ui/core/*”会受到限制也是。

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

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

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

【问题讨论】:

    标签: javascript eslint lint


    【解决方案1】:

    我想用 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/*']
          }
        ]
    

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

    【讨论】:

      【解决方案2】:

      您可以对某些文件路径使用覆盖

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

      【讨论】:

        猜你喜欢
        • 2021-03-07
        • 2011-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-21
        • 1970-01-01
        • 2013-10-09
        相关资源
        最近更新 更多