react-code-validator
Version:
A CLI tool to validate React code for best practices, performance, and accessibility.
77 lines (67 loc) ⢠2.27 kB
JavaScript
import { ESLint } from "eslint";
import chalk from "chalk";
import fs from "fs-extra";
export async function validateCode(projectPath, fix = false) {
if (!fs.existsSync(projectPath)) {
console.log(chalk.red("ā Error: Path does not exist!"));
return;
}
console.log(chalk.yellow(`š Checking project: ${projectPath}\n`));
try {
const eslint = new ESLint({
allowInlineConfig: false, // ā
Ensures ESLint ignores inline config comments
overrideConfig: {
// ā
Forces ESLint to use this config only
root: true,
env: { browser: true, es2021: true, node: true },
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
ecmaFeatures: { jsx: true },
},
extends: [
"eslint:recommended",
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended",
],
rules: {
"react/prop-types": "warn",
"react/no-unused-state": "warn",
"react-hooks/exhaustive-deps": "warn",
"jsx-a11y/alt-text": "warn",
},
},
fix,
});
const filesToLint = [`${projectPath}/**/*.{js,jsx,ts,tsx}`];
const results = await eslint.lintFiles(filesToLint);
if (fix) {
await ESLint.outputFixes(results);
console.log(chalk.green("ā
Issues fixed successfully!"));
}
if (results.length === 0) {
console.log(
chalk.green("\nš No issues found! Your React code is clean.")
);
return;
}
results.forEach((result) => {
if (result.messages.length) {
console.log(chalk.red(`\nā Issues found in: ${result.filePath}`));
result.messages.forEach((msg) => {
console.log(
`${chalk.yellow("ā ļø ")} ${chalk.cyan(msg.message)} (${msg.ruleId})`
);
});
}
});
const errorCount = results.reduce((sum, file) => sum + file.errorCount, 0);
if (errorCount > 0) {
console.log(chalk.red(`\nšØ Total Issues Found: ${errorCount}`));
}
} catch (error) {
console.log(chalk.red("ā ļø ESLint encountered an error:"));
console.error(error.message); // ā
Shows only the actual error message
}
}