Code Validation Fundamentals
Code validation is the process of automatically checking code for potential errors, style violations, and quality issues. Implementing comprehensive validation tools in your development workflow can significantly improve code quality, reduce bugs, and enhance team productivity.
π― Why Code Validation Matters
π Early Bug Detection
Catch errors and potential issues before they reach production
π Consistent Code Style
Enforce coding standards across teams and projects
π Improved Performance
Identify performance bottlenecks and optimization opportunities
π Enhanced Security
Detect security vulnerabilities and unsafe patterns
π₯ Better Collaboration
Standardized code makes reviews faster and more effective
β‘ Faster Development
Automated checks reduce time spent on manual code reviews
π Types of Code Validation
Different validation approaches address various aspects of code quality.
π Linting
Static analysis for code quality and style
- Syntax error detection
- Code style enforcement
- Best practice recommendations
- Potential bug identification
π¨ Formatting
Automatic code formatting for consistency
- Indentation standardization
- Line length management
- Spacing and alignment
- Import organization
π Static Analysis
Advanced code analysis without execution
- Type checking
- Complexity analysis
- Security vulnerability scanning
- Performance issue detection
π§ͺ Testing
Automated testing and validation
- Unit test execution
- Integration testing
- Code coverage analysis
- Regression testing
ESLint Mastery
βοΈ ESLint Configuration
Configure ESLint for maximum effectiveness in your JavaScript/TypeScript projects.
π Basic ESLint Configuration
// .eslintrc.js
module.exports = {
// Environment defines global variables
env: {
browser: true,
es2021: true,
node: true,
jest: true
},
// Extends predefined rule sets
extends: [
'eslint:recommended',
'@typescript-eslint/recommended',
'prettier' // Must be last
],
// Parser for modern JavaScript
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
ecmaFeatures: {
jsx: true
}
},
// Custom rules
rules: {
// Possible Errors
'no-console': 'warn',
'no-debugger': 'error',
'no-unused-vars': 'error',
// Best Practices
'eqeqeq': ['error', 'always'],
'no-eval': 'error',
'no-implied-eval': 'error',
// Stylistic Issues
'indent': ['error', 4],
'quotes': ['error', 'single'],
'semi': ['error', 'always'],
// React specific (if using)
'react/prop-types': 'off',
'react/react-in-jsx-scope': 'off'
},
// Settings for specific plugins
settings: {
react: {
version: 'detect'
}
}
};
π¦ Advanced Configuration with Plugins
// package.json
{
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.0",
"eslint-config-prettier": "^8.0.0",
"eslint-plugin-import": "^2.0.0",
"eslint-plugin-jsx-a11y": "^6.0.0",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.0.0",
"eslint-plugin-react-hooks": "^4.0.0",
"prettier": "^2.0.0"
},
"scripts": {
"lint": "eslint src --ext .js,.jsx,.ts,.tsx",
"lint:fix": "eslint src --ext .js,.jsx,.ts,.tsx --fix",
"format": "prettier --write src/**/*.{js,jsx,ts,tsx,json,css,md}"
}
}
// .eslintrc.js with advanced plugins
module.exports = {
extends: [
'eslint:recommended',
'@typescript-eslint/recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
'plugin:jsx-a11y/recommended',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:node/recommended',
'prettier' // Must be last
],
plugins: [
'@typescript-eslint',
'react',
'react-hooks',
'jsx-a11y',
'import',
'node'
],
rules: {
// Import organization
'import/order': ['error', {
groups: [
'builtin',
'external',
'internal',
'parent',
'sibling',
'index'
],
'newlines-between': 'always'
}],
// Accessibility
'jsx-a11y/alt-text': 'error',
'jsx-a11y/anchor-has-content': 'error',
// Node.js
'node/no-missing-import': 'off', // Handled by TypeScript
'node/no-unsupported-features/es-syntax': 'off'
},
settings: {
'import/resolver': {
typescript: {}
}
}
};
π Essential ESLint Rules
Key rules for maintaining high code quality and preventing common mistakes.
π¨ Error Prevention
// Prevent common errors
{
"rules": {
// Variable issues
"no-undef": "error", // Disallow undefined variables
"no-unused-vars": "error", // Disallow unused variables
"no-redeclare": "error", // Disallow variable redeclaration
// Function issues
"no-dupe-args": "error", // Disallow duplicate function args
"no-duplicate-imports": "error", // Disallow duplicate imports
// Logic errors
"no-cond-assign": "error", // Disallow assignment in conditionals
"no-constant-condition": "error", // Disallow constant conditions
"no-unreachable": "error", // Disallow unreachable code
// Security
"no-eval": "error", // Disallow eval()
"no-implied-eval": "error", // Disallow implied eval
"no-new-func": "error" // Disallow new Function()
}
}
β¨ Code Quality
// Improve code quality
{
"rules": {
// Best practices
"eqeqeq": ["error", "always"], // Require === and !==
"no-console": "warn", // Warn about console statements
"no-debugger": "error", // Disallow debugger statements
"no-var": "error", // Require let/const instead of var
// Complexity
"complexity": ["error", 10], // Limit cyclomatic complexity
"max-depth": ["error", 4], // Limit nesting depth
"max-lines-per-function": ["error", 50], // Limit function length
// Performance
"no-loop-func": "error", // Disallow functions in loops
"prefer-const": "error", // Prefer const over let
"no-unused-expressions": "error" // Disallow unused expressions
}
}
π¨ Style Consistency
// Enforce consistent style
{
"rules": {
// Formatting
"indent": ["error", 2], // 2-space indentation
"quotes": ["error", "single"], // Single quotes
"semi": ["error", "always"], // Require semicolons
"comma-dangle": ["error", "never"], // No trailing commas
// Spacing
"space-before-blocks": "error", // Space before blocks
"space-infix-ops": "error", // Space around operators
"keyword-spacing": "error", // Space after keywords
// Line breaks
"brace-style": ["error", "1tbs"], // One true brace style
"object-curly-spacing": ["error", "always"], // Space in objects
// Naming
"camelcase": "error", // CamelCase variables
"new-cap": "error" // Capitalize constructors
}
}
π ESLint in Development Workflows
Integrate ESLint into your development process for maximum benefit.
π― Pre-commit Hooks
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write",
"git add"
]
}
}
// .huskyrc or .husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
π§ IDE Integration
// VS Code settings.json
{
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
],
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
// WebStorm/IntelliJ
// - Install ESLint plugin
// - Enable automatic ESLint configuration
// - Set up file watchers for auto-fix
// - Configure pre-commit hooks
π CI/CD Integration
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: Run ESLint
run: npm run lint
- name: Run Prettier check
run: npx prettier --check src/**/*.{js,jsx,ts,tsx}
# GitLab CI
# .gitlab-ci.yml
lint:
image: node:16
script:
- npm ci
- npm run lint
- npx prettier --check src/**/*.{js,jsx,ts,tsx}
Prettier Code Formatting
βοΈ Prettier Configuration
Configure Prettier for consistent code formatting across your team.
π§ Prettier with ESLint
// eslint.config.js - Flat config
import js from '@eslint/js';
import prettierConfig from 'eslint-config-prettier';
export default [
js.configs.recommended,
prettierConfig, // Disables conflicting rules
{
rules: {
// Your custom rules here
'no-console': 'warn'
}
}
];
// package.json scripts
{
"scripts": {
"format": "prettier --write src/**/*.{js,jsx,ts,tsx,json,css,md}",
"format:check": "prettier --check src/**/*.{js,jsx,ts,tsx,json,css,md}",
"lint": "eslint src --ext .js,.jsx,.ts,.tsx",
"lint:fix": "eslint src --ext .js,.jsx,.ts,.tsx --fix"
}
}
// Combined lint and format
{
"scripts": {
"code:check": "npm run lint && npm run format:check",
"code:fix": "npm run lint:fix && npm run format"
}
}