【问题标题】:Eslint rule/Vscode setting to prevent importing folders without indexEslint规则/Vscode设置防止导入没有索引的文件夹
【发布时间】:2021-12-20 09:26:26
【问题描述】:

问题:

是否有 ESLint 规则强制在导入时使用 */index

示例:

文件结构:

utils/
   - index.js
   - a.js
   - b.js

main.js

main.js

// WRONG
import utils from "./utils";

// OK 
import utils from "./utils/index";

为什么

我需要这个,因为我的项目在 typescript 编译后使用tscpaths 将绝对路径替换为相对路径,但是由于某种原因,当*/index 不存在时它不会替换。

另类

如果规则不存在,是否有一个 vscode 设置会在自动导入中自动添加index

【问题讨论】:

    标签: javascript typescript visual-studio-code eslint tsc


    【解决方案1】:

    选项 1,重组您的项目,以便没有要导入的 index.js

    选项 2,如果没有太多文件夹存在此问题,您可以为 no-internal-imports 规则编写配置,以便按名称导入文件夹被视为“内部引用”。这可能是最糟糕的解决方案,因为没有自动修复并且添加新文件夹需要更新 eslint 配置,但这可能有助于作为选项提及

    选项 3,创建执行此操作的 no-useless-path-segments rule 的修改版本,它当前具有您想要的相反逻辑,因此您将修改第 95-108 行周围的代码以检查导入是否不是索引导入但解决一个建议修复:

    // assuming your rule has an option called enforceIndex
    if (options && options.enforceIndex && !regexUnnecessaryIndex.test(importPath)) {
        // if the import path is not pointing to an index file check if it resolves to a path that looks like an index file
        const resolved_path = resolve(importPath, context);
        if(regexUnnecessaryIndex.test(resolved_path)){
            // if the resolved_path resolves to something that looks like an index then suggest adding /index
            return reportWithProposedPath(`${importPath}/index`);
        }
    }
    

    可能会联系那个 eslint 包的团队,询问他们是否愿意添加对该逻辑的支持,因为它可能会出现在其他人身上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 2019-05-02
      • 2022-01-13
      • 2016-06-20
      • 2020-06-05
      • 2020-12-02
      相关资源
      最近更新 更多