You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否有ESLint插件可高亮非最优长导入路径并强制使用短路径?

存在满足需求的ESLint插件/规则

你可以通过以下两种方式实现禁止非最优长路径导入、强制使用最短顶层路径的需求:

1. 使用 eslint-plugin-prefer-import-from-index 插件

这个插件专门针对你的场景设计,会自动检测是否可通过上层index.ts导入模块,若存在则禁止直接导入子模块。

安装与配置

  • 安装插件:
    npm install eslint-plugin-prefer-import-from-index --save-dev
    
  • 在ESLint配置文件(如.eslintrc.json)中启用规则:
    {
      "plugins": ["prefer-import-from-index"],
      "rules": {
        "prefer-import-from-index/prefer-import-from-index": "error"
      }
    }
    

2. 使用 eslint-plugin-import 内置规则 no-internal-modules

如果你已经在使用eslint-plugin-import,可以直接用它的内置规则实现类似效果,禁止导入指定目录的内部子模块,仅允许从顶层index.ts导入。

配置示例

在ESLint配置文件中添加:

{
  "rules": {
    "import/no-internal-modules": [
      "error",
      {
        "forbid": [
          "**/components/*",
          "!**/components/index.ts"
        ]
      }
    ]
  }
}

上述配置会禁止导入components目录下的任何子模块(如components/foo、components/foo/bar),仅允许从components/index.ts(即./components)导入。

内容的提问来源于stack exchange,提问作者Onkeltem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:14:57