feat: add custom ESLint rule restrict-import-depth (#110)

This commit is contained in:
doprz
2024-02-27 23:52:45 -06:00
parent 87799d8f02
commit 8c069b7ad3
6 changed files with 65 additions and 1 deletions

View File

@@ -18,7 +18,14 @@
"@unocss",
"prettier",
],
"plugins": ["import", "jsdoc", "react-prefer-function-component", "@typescript-eslint", "simple-import-sort"],
"plugins": [
"import",
"jsdoc",
"react-prefer-function-component",
"@typescript-eslint",
"simple-import-sort",
"restrict-import-depth",
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly",
@@ -201,5 +208,6 @@
"@typescript-eslint/consistent-type-imports": "error",
"simple-import-sort/imports": "error",
"simple-import-sort/exports": "error",
"restrict-import-depth/restrict-import-depth": "error",
},
}

View File

@@ -0,0 +1,5 @@
module.exports = {
rules: {
'restrict-import-depth': require('./restrict-import-depth'),
},
};

View File

@@ -0,0 +1,6 @@
{
"name": "eslint-plugin-restrict-import-depth",
"version": "0.1.0",
"description": "ESLint plugin to restrict the depth of import statements",
"main": "index.js"
}

View File

@@ -0,0 +1,35 @@
/**
* @fileoverview Custom ESLint rule to restrict imports from accessing files more than 2 directories up.
*/
'use strict';
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Restrict imports from accessing files more than 2 directories up.',
category: 'Best Practices',
recommended: true,
},
fixable: null,
schema: [],
},
create: function (context) {
return {
ImportDeclaration(node) {
const importPath = node.source.value;
if (importPath.startsWith('../')) {
const depth = importPath.match(/\.\.\//g).length;
if (depth > 2) {
context.report({
node,
message: 'Importing files more than 2 directories up is not allowed.',
});
}
}
},
};
},
};

View File

@@ -94,6 +94,7 @@
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-prefer-function-component": "^3.3.0",
"eslint-plugin-react-refresh": "^0.4.5",
"eslint-plugin-restrict-import-depth": "file:custom-eslint-rules",
"eslint-plugin-simple-import-sort": "^12.0.0",
"eslint-plugin-storybook": "^0.6.15",
"husky": "^9.0.11",

9
pnpm-lock.yaml generated
View File

@@ -215,6 +215,9 @@ devDependencies:
eslint-plugin-react-refresh:
specifier: ^0.4.5
version: 0.4.5(eslint@8.56.0)
eslint-plugin-restrict-import-depth:
specifier: file:custom-eslint-rules
version: file:custom-eslint-rules
eslint-plugin-simple-import-sort:
specifier: ^12.0.0
version: 12.0.0(eslint@8.56.0)
@@ -13262,6 +13265,12 @@ packages:
engines: {node: '>=12.20'}
dev: true
file:custom-eslint-rules:
resolution: {directory: custom-eslint-rules, type: directory}
name: eslint-plugin-restrict-import-depth
version: 0.1.0
dev: true
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false