UNPKG

react-code-validator

Version:

A CLI tool to validate React code for best practices, performance, and accessibility.

77 lines (67 loc) • 2.27 kB
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 } }