react-code-smell-detector
v1.5.3
Published
Detect code smells in React projects - useEffect overuse, prop drilling, large components, security issues, accessibility, memory leaks, React 19 Server Components, and more
Maintainers
Readme
React Code Smell Detector
A CLI tool that analyzes React projects and detects common code smells, providing refactoring suggestions and a technical debt score.
Features
- 🔍 Detect Code Smells: Identifies common React anti-patterns (70+ smell types)
- 📊 Technical Debt Score: Grades your codebase from A to F
- 💡 Refactoring Suggestions: Actionable recommendations for each issue
- 📝 Multiple Output Formats: Console (colored), JSON, Markdown, HTML, and PDF
- 🔒 Security Scanning: Detects XSS vulnerabilities, eval usage, exposed secrets
- ♿ Accessibility Checks: Missing alt text, labels, ARIA attributes
- 🐛 Debug Cleanup: console.log, debugger, TODO/FIXME detection
- 🤖 CI/CD Ready: Exit codes and flags for pipeline integration
- 🔧 Auto-Fix: Automatically fix simple issues (console.log, var, ==, missing alt)
- 👀 Watch Mode: Re-analyze on file changes
- 📂 Git Integration: Analyze only modified files
- 🧮 Complexity Metrics: Cyclomatic and cognitive complexity scoring
- 💧 Memory Leak Detection: Find missing cleanup in useEffect
- 🔄 Import Analysis: Detect circular dependencies and barrel file issues
- 🗑️ Unused Code Detection: Find unused exports and dead imports
- 📈 Advanced Trend Analytics: ML-powered trend analysis with predictions and health scores
- 💬 Chat Notifications: Send analysis results to Slack, Discord, or custom webhooks
- 🔗 Dependency Graph Visualization: Visual SVG/HTML of component and import relationships
- 📦 Bundle Size Impact: Per-component bundle size estimates and optimization suggestions
- ⚙️ Custom Rules Engine: Define project-specific code quality rules in configuration
- 🔧 Interactive Fix Mode: Review and apply fixes one by one with diff preview
- 💬 GitHub PR Comments: Auto-comment analysis results on pull requests
- 📊 Performance Budget: Set thresholds and enforce limits in CI/CD
- 📄 PDF Report Generation: Professional, printable reports with visual analytics
- 🎯 ESLint Plugin Integration: Run detectors directly as ESLint rules
- 📚 Component Documentation: Auto-generate docs from component analysis
- ⚛️ React 19 Server Components: Detect Server/Client boundary issues
- 🔮 Context API Analysis: Detect context overuse, missing memoization, re-render issues
- 🛡️ Error Boundary Detection: Find missing ErrorBoundary and Suspense wrappers
- 📋 Form Validation Smells: Detect uncontrolled inputs, missing validation
- 🗃️ State Management Analysis: Redux/Zustand anti-patterns, selector issues
- 🧪 Testing Gap Detection: Identify complex components likely needing tests
- 🤖 AI Refactoring Suggestions: LLM-powered smart refactoring recommendations
- 🔒 Security Audit: Comprehensive vulnerability scanning (XSS, injection, secrets, crypto issues)
- ⚡ Performance Profiler: Component optimization analysis with memoization & render metrics
- 👥 Team Dashboard: Centralized view of team metrics, workload & quality trends
- 🔗 API Integration: Sync with GitHub, Slack, Jira, monitoring platforms & webhooks
- 🔍 Custom Analyzer: Define and apply project-specific code quality rules
Detected Code Smells
| Category | Detection |
|----------|-----------|
| useEffect Overuse | Multiple useEffects per component, missing cleanup, async patterns |
| Prop Drilling | Too many props, drilling depth analysis |
| Large Components | Components over 300 lines, deep JSX nesting |
| Unmemoized Calculations | .map(), .filter(), .reduce(), JSON.parse() without useMemo |
| Inline Functions | Callbacks defined inline in JSX props |
| Security Issues | dangerouslySetInnerHTML, eval(), innerHTML, exposed API keys |
| Accessibility | Missing alt text, form labels, keyboard handlers, semantic HTML |
| Debug Statements | console.log, debugger statements, TODO/FIXME comments |
| Memory Leaks | Missing cleanup for event listeners, timers, subscriptions |
| Code Complexity | Cyclomatic complexity, cognitive complexity, deep nesting |
| Import Issues | Circular dependencies, barrel file imports, excessive imports |
| Unused Code | Unused exports, dead imports |
| Custom Rules | User-defined code quality rules |
| Server Components | React 19 client/server boundary issues, async components |
| Framework-Specific | Next.js, React Native, Node.js, TypeScript issues |
| Context API | Context overuse, missing memoization, large context values |
| Error Boundaries | Missing ErrorBoundary, Suspense without fallback |
| Form Validation | Uncontrolled forms, missing validation, controlled inputs without onChange |
| State Management | Redux selector anti-patterns, derived state issues, state sync problems |
| Testing Gaps | Complex untestable components, side-effect heavy code, tight coupling |
Installation
npm install -g react-code-smell-detectorOr use as a dev dependency:
npm install -D react-code-smell-detectorUsage
Basic Analysis
react-smell /path/to/react/projectInteractive Guide
Launch an interactive tutorial to learn all features:
react-smell guideDemo Project
Create a demo project with examples of all detectable code smells:
react-smell demo
# Creates ./react-smell-demo with sample components
# Or specify a directory
react-smell demo /path/to/directoryWith Code Snippets
react-smell ./src -sOutput Formats
# Console (default - colored output)
react-smell ./src
# JSON (for CI/CD integration)
react-smell ./src -f json
# Markdown (for documentation)
react-smell ./src -f markdown -o report.md
# HTML (beautiful visual report)
react-smell ./src -f html -o report.html
# PDF (professional formatted report with charts)
react-smell ./src -f pdf -o report.pdfESLint Plugin Integration
Run code smell detection directly integrated with ESLint:
# Install ESLint if not already installed
npm install -D eslint
# Add to .eslintrc.json
{
"plugins": ["react-code-smell-detector"],
"extends": ["plugin:react-code-smell-detector/recommended"]
}
# Or use strict mode for more comprehensive checks
{
"plugins": ["react-code-smell-detector"],
"extends": ["plugin:react-code-smell-detector/strict"]
}Benefits:
- Real-time feedback in your editor
- Integrates with existing ESLint workflow
- Runs on file save or pre-commit
- Works with git hooks and CI/CD pipelines
Available ESLint Rules:
no-excessive-use-effect: Detect overuse of useEffectno-prop-drilling: Detect prop drilling patternsno-large-components: Warn on component sizeno-unmemoized-calculations: Flag unmemoized expensive operationsno-security-issues: Detect security vulnerabilitiesaccessibility-checked: Accessibility violationsno-memory-leaks: Potential memory leaksno-circular-dependencies: Circular import detectionstate-management-smell: State management anti-patterns- And 9 more rules for comprehensive coverage
Advanced Trend Analytics
Track code quality trends over time with intelligent predictions and insights:
# Enable trend analysis in baseline tracking
react-smell ./src --baseline --trend-analysis
# View detailed trend insights
react-smell ./src --baseline --trend-reportFeatures:
- Trend Direction: Automatic detection of improving, worsening, or stable trends
- Growth Metrics: Daily velocity, change rate, consistency scoring
- Predictive Analytics: Machine learning-based predictions for next 30 days
- Health Score: Overall codebase health indicator (0-100)
- Zero Smell Timeline: Estimated days to reach zero code smells
- Seasonality Detection: Identify patterns in code quality changes
- Smart Recommendations: AI-powered suggestions based on trend analysis
Trend Analysis Output:
📈 Trend Analysis
──────────────────────────────────────────────────
Current: 42 smells
Previous: 48 smells
Change: -12.5%
Trend: IMPROVING
✅ Health Score: 72/100 (good)
📊 Metrics
• Daily Velocity: 0.75 smells/day (improving)
• Consistency: 85%
• Volatility: 2.1
🔮 Predictions
• Next Month: ~35 smells
• Trajectory: DOWNWARD
• Confidence: 92%
• Days to Zero Smells: 56
✨ Improvements
• useEffect-overuse (3 fewer)
• prop-drilling (2 fewer)
💡 Recommendations
🟢 Path to Code Smell-Free Codebase
At the current improvement rate, your codebase could be
smell-free in approximately 56 days. Focus on maintaining
this momentum.Configuration:
{
"baselineEnabled": true,
"trendAnalysisEnabled": true,
"trendReportFrequency": "weekly",
"predictiveDaysLookahead": 30
}PDF Report Generation
Generate professional, printable PDF reports with visual analytics:
# Generate PDF report
react-smell ./src -f pdf -o smell-report.pdf
# Include code snippets in PDF
react-smell ./src -f pdf -o report.pdf --snippets
# Generate PDF with trend analysis
react-smell ./src -f pdf -o report.pdf --baseline --trend-analysisPDF Report Contents:
- Executive Summary with key metrics
- Technical Debt Grade with visual indicators
- Smell breakdown by type and severity
- Top affected files with risk levels
- Detailed smell analysis with code snippets
- Actionable recommendations prioritized by impact
- Trend analysis and predictions
- Estimated refactoring timeline
Visual Elements:
- Color-coded severity levels (error/warning/info)
- Grade badges with color gradients
- Data visualizations and charts
- Summary metrics in card layout
- Code snippets with syntax highlighting
- Professional typography and layout
Use Cases:
- Share reports with stakeholders
- Archive analysis history
- Print for code review meetings
- Executive dashboards
- Compliance documentation
Security Audit
Comprehensive security vulnerability scanning and compliance analysis:
# Run security audit
react-smell ./src --security-audit
# Include secret detection
react-smell ./src --security-audit --check-secrets
# Generate security report
react-smell ./src --security-audit -f json -o security-report.jsonDetects:
- XSS Vulnerabilities: dangerouslySetInnerHTML, innerHTML assignment, eval() usage
- Injection Attacks: SQL injection, command injection, regex injection patterns
- Secrets Exposure: API keys, passwords, tokens, private keys
- Cryptography Issues: Deprecated cipher functions, weak hashing (MD5, SHA1), weak random generation
- CVSS Scoring: Risk assessment with industry-standard vulnerability scoring
Output: Compliance score, risk level, critical/high/medium/low categorization, remediation suggestions
Performance Profiler
Analyze and optimize component performance characteristics:
# Profile performance metrics
react-smell ./src --performance
# Get detailed performance analysis
react-smell ./src --performance --detailed
# Export performance metrics
react-smell ./src --performance -f json -o perf-metrics.jsonAnalyzes:
- Render Time: Estimated component rendering duration
- Memory Usage: Approximate memory footprint per component
- Memoization Score: Identifies missing useMemo/useCallback opportunities (0-100)
- Render Efficiency: Optimization potential rating
- Bottleneck Detection: Identifies slow, memory-intensive, or re-render-heavy components
- Hook Usage: State and effect hook analysis for consolidation opportunities
Team Dashboard
Centralized metrics view for team collaboration and quality tracking:
# Generate team dashboard
react-smell dashboard
# Include team members
react-smell dashboard --team-members team.json
# View in CI/CD pipeline
react-smell dashboard -f json | post-to-dashboard-apiFeatures:
- Team Metrics: Member count, component ownership, average code quality
- Health Status: Excellent/Good/Fair/Poor/Critical team health indicator
- Common Issues: Top code smells affecting the team with frequency counts
- Activity Log: Recent analysis events with timestamps
- Alerts: Critical issues, component overload warnings, team workload indicators
- Ownership Tracking: Component assignment to team members
API Integration
Sync analysis results with external services, issue trackers, and monitoring platforms:
# Send to external API
react-smell ./src --send-to-api https://api.example.com --api-key sk-xxx
# Post issues to GitHub/GitLab
react-smell ./src --post-issues --github --token $GITHUB_TOKEN
# Send Slack notifications
react-smell ./src --webhook https://hooks.slack.com/services/xxx
# Check SLA compliance
react-smell ./src --check-sla ./sla-config.json
# Comment on pull requests
react-smell ./src --comment-pr --pr-number 123 --pr-token $TOKEN
# Sync to monitoring platform
react-smell ./src --sync-metrics https://metrics.service.comIntegrations:
- GitHub Issues, GitHub Pull Request Comments, GitHub Actions
- GitLab Issues, Merge Request comments
- Jira issue creation and linking
- Slack notifications and dashboards
- Discord webhooks
- Datadog, New Relic, and other APM platforms
- Custom REST API endpoints
- SLA monitoring and compliance checking
Custom Analyzer
Define and apply project-specific code quality rules:
# Create custom rules
react-smell init --custom-rules
# Apply custom rules
react-smell ./src --custom-rules ./custom-rules.json
# Validate rules before applying
react-smell ./src --validate-rules ./custom-rules.jsonExample Custom Rules:
{
"customRules": [
{
"id": "no-magic-numbers",
"name": "No Magic Numbers",
"pattern": "[0-9]{3,}",
"severity": "warning",
"message": "Magic number found",
"suggestion": "Extract to named constant",
"enabled": true
},
{
"id": "naming-convention",
"name": "Component Naming",
"pattern": "^[a-z].*\\.tsx$",
"severity": "warning",
"message": "Component name must start with uppercase",
"suggestion": "Use PascalCase",
"enabled": true
},
{
"id": "no-console-in-prod",
"name": "No Console in Production",
"pattern": "console\\.(log|warn|error)",
"severity": "info",
"message": "Console statement detected",
"suggestion": "Remove or use logger",
"enabled": false
}
]
}Rule Features:
- String and regex pattern matching
- File/component/function/expression scope filtering
- Include/exclude patterns for file filtering
- Enable/disable rules individually
- Custom severity levels
- Multi-line pattern matching
Configuration
Create a .smellrc.json file:
react-smell initOr create manually:
{
"maxUseEffectsPerComponent": 3,
"maxPropDrillingDepth": 3,
"maxComponentLines": 300,
"maxPropsCount": 7
}Create a .smellrc.json file:
react-smell initOr create manually:
{
"maxUseEffectsPerComponent": 3,
"maxPropDrillingDepth": 3,
"maxComponentLines": 300,
"maxPropsCount": 7
}CLI Options
| Option | Description | Default |
|--------|-------------|---------|
| -f, --format <format> | Output format: console, json, markdown, html, pdf | console |
| -s, --snippets | Show code snippets in output | false |
| -c, --config <file> | Path to config file | .smellrc.json |
| --ci | CI mode: exit with code 1 if any issues | false |
| --fail-on <severity> | Exit code 1 threshold: error, warning, info | error |
| --fix | Auto-fix simple issues (console.log, var, ==, alt) | false |
| --watch | Watch mode: re-analyze on file changes | false |
| --changed | Only analyze git-modified files | false |
| --max-effects <number> | Max useEffects per component | 3 |
| --max-props <number> | Max props before warning | 7 |
| --max-lines <number> | Max lines per component | 300 |
| --include <patterns> | Glob patterns to include | **/*.tsx,**/*.jsx |
| --exclude <patterns> | Glob patterns to exclude | node_modules,dist |
| -o, --output <file> | Write output to file | - |
| --baseline | Enable baseline tracking and trend analysis | false |
| --trend-analysis | Show detailed trend analysis and predictions | false |
| --trend-report | Generate comprehensive trend report | false |
| --slack <url> | Slack webhook URL for notifications | - |
| --discord <url> | Discord webhook URL for notifications | - |
| --webhook <url> | Generic webhook URL for notifications | - |
| --webhook-threshold <number> | Only notify if smells exceed threshold | 10 |
| --graph | Generate dependency graph visualization | false |
| --graph-format <format> | Graph output format: svg, html | html |
| --bundle | Analyze bundle size impact per component | false |
| --rules <file> | Custom rules configuration file | - |
| --fix-interactive | Interactive fix mode: review fixes one by one | false |
| --fix-preview | Preview fixable issues without applying | false |
| --pr-comment | Generate PR comment (for GitHub Actions) | false |
| --budget | Check against performance budget | false |
| --budget-config <file> | Path to budget config file | .smellbudget.json |
| --docs | Generate component documentation | false |
| --docs-format <format> | Documentation format: markdown, html, json | markdown |
| --ai | Enable AI-powered refactoring suggestions | false |
| --ai-key <key> | API key for AI provider | - |
| --ai-model <model> | AI model to use (gpt-4, claude-3-sonnet, etc.) | gpt-4 |
Auto-Fix
Automatically fix simple issues:
# Fix and show remaining issues
react-smell ./src --fix
# Fix only (no report)
react-smell ./src --fix -f json > /dev/nullFixable issues:
console.log,console.debug, etc. → Removedvar x = 1→let x = 1a == b→a === b<img src="...">→<img src="..." alt="">
Watch Mode
Re-analyze on every file change:
react-smell ./src --watchGit Integration
Only analyze modified files:
react-smell ./src --changedBaseline Tracking & Trend Analysis
Track code smell trends over time with automatic baseline recording:
# Enable baseline tracking
react-smell ./src --baseline
# Output includes trend analysis
📊 Code Smell Trend Analysis
──────────────────────────
Latest Run: 42 total smells
Trend: IMPROVING
Previous Run: 48 smells
Improved: 6 issues fixed
Worsened: 0 new issuesFeatures:
- Stores history in
.smellrc-baseline.json - Tracks timestamps, commit hashes, and author names
- Automatic trend calculation (improving/worsening/stable)
- Keeps last 50 records with automatic cleanup
- Perfect for CI/CD pipelines to monitor progress
Configuration:
{
"baselineEnabled": true,
"baselineThreshold": 5
}Chat Notifications
Send analysis results to Slack, Discord, or custom webhooks:
Slack Integration
react-smell ./src --slack https://hooks.slack.com/services/YOUR/WEBHOOK
# With threshold (only notify if issues exceed limit)
react-smell ./src --slack $SLACK_URL --webhook-threshold 20Features:
- Rich formatted messages with severity levels
- Includes branch, commit hash, and author info
- Shows top 5 issue types by frequency
- Color-coded severity (Critical/High/Medium/Low)
Discord Integration
react-smell ./src --discord https://discord.com/api/webhooks/123/abc
# With environment variable
export REACT_SMELL_DISCORD_WEBHOOK=https://...
react-smell ./src --discord $REACT_SMELL_DISCORD_WEBHOOKFeatures:
- Embedded messages with visual design
- Color-coded smells by severity
- Full metadata included (branch, author, commit)
Generic Webhooks
react-smell ./src --webhook https://example.com/webhook
# Custom platform webhooks
react-smell ./src --webhook $CUSTOM_URL --webhook-threshold 15Environment Variables:
export REACT_SMELL_SLACK_WEBHOOK=https://...
export REACT_SMELL_DISCORD_WEBHOOK=https://...
export REACT_SMELL_WEBHOOK=https://...CI/CD Example with Notifications:
# Run analysis, track baseline, and notify on failures
react-smell ./src \
--baseline \
--slack $SLACK_WEBHOOK \
--webhook-threshold 10 \
--ciDependency Graph Visualization
Generate interactive dependency graphs showing component and file relationships:
# Generate dependency graph
react-smell ./src --graph
# Auto-generates: dependency-graph.htmlFeatures:
- Visual representation of file imports and dependencies
- Circular dependency detection and highlighting
- Force-directed layout for clarity
- Exportable SVG or HTML format
- Legend showing node types and relationships
Example Usage:
# Generate and analyze all at once
react-smell ./src --graph --bundle --baseline --ciBundle Size Impact Analysis
Estimate per-component bundle size impact:
# Analyze bundle impact
react-smell ./src --bundle
# Auto-generates: bundle-analysis.htmlFeatures:
- Estimated size per component (in bytes)
- Line of code (LOC) analysis
- Dependency complexity scoring
- Impact level classification (low/medium/high/critical)
- Recommendations for optimization
- Breakdown of largest components
Impact Levels:
- 🟢 Low: <2KB, <150 LOC, low complexity
- 🟡 Medium: 2-5KB, 150-300 LOC, medium complexity
- 🟠 High: 5-10KB, 300-500 LOC, high complexity
- 🔴 Critical: >10KB, >500 LOC, very complex
Custom Rules Engine
Define project-specific code quality rules:
Configuration File (.smellrc-rules.json):
{
"rules": [
{
"name": "no-hardcoded-strings",
"description": "Prevent hardcoded strings (use i18n)",
"severity": "warning",
"pattern": "\"(hello|world|test)\"",
"patternType": "regex",
"enabled": true
},
{
"name": "require-display-name",
"description": "All components must have displayName",
"severity": "info",
"pattern": "displayName",
"patternType": "text",
"enabled": true
}
]
}CLI Usage:
# Use custom rules
react-smell ./src --rules .smellrc-rules.json
# Combined with other features
react-smell ./src --rules .smellrc-rules.json --format json --ciRule Properties:
| Property | Type | Description |
|----------|------|-------------|
| name | string | Unique rule identifier |
| description | string | Human-readable explanation |
| severity | string | error, warning, or info |
| pattern | string | Regex or text pattern |
| patternType | string | regex, text, or ast |
| enabled | boolean | Enable/disable rule |
Pattern Types:
- regex: Regular expression matching (e.g.,
"hardcoded.*string") - text: Simple string matching
- ast: Babel AST node type matching (e.g.,
FunctionExpression)
Real-World Examples:
{
"rules": [
{
"name": "no-console-in-production",
"pattern": "console\\.(log|warn|info)",
"patternType": "regex",
"severity": "error"
},
{
"name": "enforce-prop-types",
"pattern": "PropTypes",
"patternType": "text",
"severity": "warning",
"message": "Consider using TypeScript instead of PropTypes"
},
{
"name": "limit-nesting",
"description": "Flag deeply nested JSX",
"pattern": "<.*>.*<.*>.*<.*>.*<.*>.*<",
"patternType": "regex",
"severity": "info"
}
]
}Interactive Fix Mode
Review and apply fixes one by one with diff preview:
# Interactive mode - review each fix
react-smell ./src --fix-interactive
# Preview fixable issues without applying
react-smell ./src --fix-previewOutput:
🔧 Interactive Fix Mode
Found 5 fixable issue(s). Review each one:
Commands: [y]es, [n]o, [a]ll, [q]uit
────────────────────────────────────────────────────────────────
src/utils/helper.ts:15
debug-statement: console.log found
Fix: Remove console.log/debugger statements
- console.log('debug:', value);
+ (line removed)
Apply this fix? [y/n/a/q]: y
✓ AppliedGitHub PR Comments
Auto-comment code smell analysis on pull requests:
# Generate PR comment (outputs markdown)
react-smell ./src --pr-comment
# In GitHub Actions (auto-posts to PR)
react-smell ./src --pr-comment --ciGitHub Actions workflow:
- name: Analyze Code
run: npx react-smell ./src --pr-comment --ci
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}Performance Budget
Set thresholds for code quality and enforce in CI/CD:
# Create budget config
react-smell init-budget
# Check against budget
react-smell ./src --budget
# With custom config
react-smell ./src --budget --budget-config my-budget.jsonBudget config (.smellbudget.json):
{
"maxErrors": 0,
"maxWarnings": 10,
"minScore": 70,
"minGrade": "C",
"maxSmellsPerFile": 5,
"maxByType": {
"useEffect-overuse": 3,
"prop-drilling": 5
}
}Output:
✗ Performance budget check failed
Violations:
✗ Errors (2) exceeds budget (0)
⚠ Warnings (15) exceeds budget (10)
Checks: 3 passed, 2 failedComponent Documentation
Auto-generate documentation from component analysis:
# Generate markdown docs
react-smell docs ./src
# Generate HTML docs
react-smell docs ./src -f html
# Output to specific directory
react-smell docs ./src -f html -o ./docsOutput (COMPONENTS.md):
# Component Documentation
## Summary
| Metric | Value |
|--------|-------|
| Total Components | 25 |
| Technical Debt Grade | B |
## Components
#### Button
📄 `components/Button.tsx`
| Metric | Value |
|--------|-------|
| Lines | 45 |
| Complexity | 🟢 Low |
| Maintainability | 🟢 Good |
**Hooks:** useState (2), useCallback (1)React 19 Server Components
Detect Server/Client component boundary issues:
# Enabled by default for app/ directory components
react-smell ./srcDetected issues:
server-component-hooks: Using useState/useEffect in Server Componentsserver-component-events: Using onClick/onChange in Server Componentsserver-component-browser-api: Using window/document in Server Componentsasync-client-component: Async function in 'use client' componentmixed-directives: Both 'use client' and 'use server' in same file
Example Output
╔══════════════════════════════════════════════════════════════╗
║ 🔍 React Code Smell Detector Report ║
╚══════════════════════════════════════════════════════════════╝
📊 Technical Debt Score
Grade: C ███████████████░░░░░ 73/100
Breakdown:
⚡ useEffect: ██████████ 100
🔗 Prop Drilling: ██████████ 100
📐 Component Size:███████░░░ 70
💾 Memoization: ░░░░░░░░░░ 0
Estimated refactor time: 1-2 hours
📈 Summary
Files analyzed: 10
Components found: 21
Total issues: 5 warning(s), 26 infoProgrammatic API
import {
analyzeProject,
reportResults,
// PDF Reporting
generatePDFReport,
// Trend Analytics
analyzeTrends,
formatTrendAnalysis,
// Interactive fixing
runInteractiveFix,
previewFixes,
// PR Comments
generatePRComment,
postPRComment,
// Performance Budget
loadBudget,
checkBudget,
formatBudgetReport,
// Documentation
generateComponentDocs,
writeComponentDocs,
// Baseline & Trends
recordBaseline,
initializeBaseline,
} from 'react-code-smell-detector';
const result = await analyzeProject({
rootDir: './src',
config: {
maxUseEffectsPerComponent: 3,
maxComponentLines: 300,
checkUnusedCode: true,
checkServerComponents: true, // React 19
},
});
console.log(`Grade: ${result.debtScore.grade}`);
console.log(`Total issues: ${result.summary.totalSmells}`);
// Generate PDF report
await generatePDFReport(result, {
outputPath: './report.pdf',
rootDir: './src',
includeCharts: true,
includeCodeSnippets: true,
title: 'Code Quality Report',
});
// Record baseline for trend tracking
initializeBaseline('./');
const baselineRecord = recordBaseline('./', result.smells);
// Analyze trends from baseline history
// (requires multiple baseline recordings over time)
import { BaselineData } from 'react-code-smell-detector';
const baselineData: BaselineData = JSON.parse(
fs.readFileSync('.smellrc-baseline.json', 'utf-8')
);
const trendAnalysis = analyzeTrends(baselineData);
console.log(formatTrendAnalysis(trendAnalysis));
// Check against performance budget
const budget = await loadBudget();
const budgetResult = checkBudget(result, budget);
if (!budgetResult.passed) {
console.log(formatBudgetReport(budgetResult));
}
// Generate documentation
const docsPath = await writeComponentDocs(result, './src', {
format: 'markdown',
includeSmells: true,
});
// Generate PR comment
const prComment = generatePRComment(result, './src');
// Or use the reporter for any format
const report = reportResults(result, {
format: 'markdown',
showCodeSnippets: true,
rootDir: './src',
});Trend Analytics API:
import { TrendAnalysis, TrendPrediction } from 'react-code-smell-detector';
// Access trend data
const currentHealth = trendAnalysis.healthScore; // HealthScore
const predictions = trendAnalysis.predictions; // TrendPrediction
const metrics = trendAnalysis.metrics; // TrendMetrics
const recommendations = trendAnalysis.recommendations; // TrendRecommendation[]
// Timeline to zero smells
if (predictions.daysToZeroSmells) {
console.log(`Projected zero smells in ${predictions.daysToZeroSmells} days`);
}
// Access velocity and consistency metrics
console.log(`Daily Velocity: ${metrics.velocityPerDay} smells/day`);
console.log(`Consistency: ${metrics.consistency}%`);CI/CD Integration
The tool provides flexible exit codes and notification capabilities for CI/CD pipelines:
# Fail on any issues (strict mode)
react-smell ./src --ci
# Fail on warnings and errors (default: errors only)
react-smell ./src --fail-on warning
# Generate HTML report and fail on errors
react-smell ./src -f html -o report.html --fail-on error
# Track trends and notify
react-smell ./src --baseline --slack $SLACK_WEBHOOK --ciGitHub Actions Example
name: Code Quality
on: [push, pull_request]
jobs:
code-smells:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # For git baseline tracking
- uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Check code smells with baseline tracking
run: npx react-smell ./src -f html -o smell-report.html --baseline --fail-on warning
- name: Notify Slack on failure
if: failure()
run: npx react-smell ./src --slack ${{ secrets.SLACK_WEBHOOK }} --webhook-threshold 10
- name: Upload report
uses: actions/upload-artifact@v4
if: always()
with:
name: code-smell-report
path: smell-report.htmlGitLab CI Example
code-quality:
image: node:20
script:
- npm ci
- npx react-smell ./src --baseline --fail-on warning
artifacts:
reports:
codequality: code-smell-report.json
after_script:
- npx react-smell ./src --discord $DISCORD_WEBHOOK || trueIgnoring Issues
Use @smell-ignore comments to suppress specific issues:
// @smell-ignore
console.log('This debug statement is ignored');
// @smell-ignore debug-statement
console.log('Only ignores debug-statement type');
// @smell-ignore *
const risky = eval('1+1'); // All issues on next line ignoredTechnical Debt Score
The score is calculated based on:
| Category | Weight | Description | |----------|--------|-------------| | useEffect Usage | 30% | Penalized for overuse, missing cleanup | | Prop Drilling | 25% | Penalized for deep drilling, too many props | | Component Size | 25% | Penalized for large components, deep nesting | | Memoization | 20% | Penalized for unmemoized calculations |
Grades:
- A: 90-100 (Excellent)
- B: 80-89 (Good)
- C: 70-79 (Needs Improvement)
- D: 60-69 (Poor)
- F: <60 (Critical)
License
MIT
