Public commit
This commit is contained in:
62
eslint-local-rules/no-deep-relative-import.ts
Normal file
62
eslint-local-rules/no-deep-relative-import.ts
Normal file
@ -0,0 +1,62 @@
|
||||
import type { Rule } from "eslint"
|
||||
|
||||
interface RuleOptions {
|
||||
/**
|
||||
* The maximum number of times a relative path import can go to the parent directory.
|
||||
*/
|
||||
maxDepth?: number
|
||||
}
|
||||
|
||||
const rule: Rule.RuleModule = {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
docs: {
|
||||
description:
|
||||
"Bans relative path imports that go to the parent directory too many times",
|
||||
category: "Best Practices",
|
||||
recommended: true,
|
||||
},
|
||||
fixable: "code",
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
maxDepth: {
|
||||
type: "integer",
|
||||
minimum: 1,
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
create(context) {
|
||||
const { maxDepth = 3 } = (context.options[0] || {}) as RuleOptions
|
||||
const errorMessage = `Relative path imports cannot go to the parent directory more than ${maxDepth} levels`
|
||||
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
const { source } = node
|
||||
if (
|
||||
source.type === "Literal" &&
|
||||
typeof source.value === "string" &&
|
||||
source.value.startsWith("..")
|
||||
) {
|
||||
const depth = source.value.match(/\.\.\//g)?.length ?? 0
|
||||
if (depth > maxDepth) {
|
||||
context.report({
|
||||
node: source,
|
||||
message: errorMessage,
|
||||
fix(fixer) {
|
||||
const newValue = (source.value as string)!.replace(/\.\.\//g, "")
|
||||
return fixer.replaceText(source, `'${newValue}'`)
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export default rule
|
Reference in New Issue
Block a user