[英]Eslint rule/Vscode setting to prevent importing folders without index
Is there an ESLint rule to enforce usage of */index
on imports.是否有 ESLint 规则来强制在导入时使用
*/index
。
File structure:文件结构:
utils/
- index.js
- a.js
- b.js
main.js
main.js主文件
// WRONG
import utils from "./utils";
// OK
import utils from "./utils/index";
I need this because my project is using tscpaths
to replace absolute paths with relative paths after typescript compilation, but, for some reason, it doesn't replace when the */index
is not present.我需要这个,因为我的项目在打字稿编译后使用
tscpaths
用相对路径替换绝对路径,但是由于某种原因,当*/index
不存在时它不会替换。
If the rule doesn't exist, is there a vscode setting that would automatically add the index
in auto imports?如果规则不存在,是否有 vscode 设置会自动在自动导入中添加
index
?
Option 1, restructure your project so there are no index.js
to import.选项 1,重组您的项目,以便没有要导入的
index.js
。
Option 2, If there aren't too many folders where this is an issue you can write a config for no-internal-imports
rule such that importing a folder by name is considered an "internal reference".选项 2,如果存在此问题的文件夹不多,您可以为
no-internal-imports
规则编写配置,以便按名称导入文件夹被视为“内部引用”。 This is probably the worst solution since there is no auto-fix and adding new folders requires updating the eslint config but this might be helpful to mention as an option这可能是最糟糕的解决方案,因为没有自动修复,添加新文件夹需要更新 eslint 配置,但这可能有助于提及作为一个选项
Option 3, create a modified version of the no-useless-path-segments
rule that does this, it currently has the opposite logic as you want so you would modify the code around lines 95-108 to check if the import isn't an index import but resolves to one suggest the fix:选项 3,创建执行此操作的
no-useless-path-segments
规则的修改版本,它当前具有与您想要的相反的逻辑,因此您将修改第 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`);
}
}
possibly approach the team of that eslint package and ask if they'd be willing to add support for that logic as it may come up for other people.可能会联系该 eslint 包的团队并询问他们是否愿意添加对该逻辑的支持,因为它可能会出现在其他人身上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.