Skip to content

Code Style

ThanuMahee12 edited this page Oct 20, 2025 · 1 revision

Code Style & Formatting

Guide to code formatting and style conventions for this project.

Overview

This project uses Prettier for code formatting and ESLint for code quality checks. All code must pass both format and lint checks before being deployed.

graph LR
    A[Write Code] --> B[Run Prettier]
    B --> C[Run ESLint]
    C --> D{All Checks Pass?}
    D -->|Yes| E[Commit & Push]
    D -->|No| F[Fix Issues]
    F --> B
    E --> G[CI/CD Pipeline]
    G --> H{Format & Lint Check}
    H -->|Pass| I[Deploy to Firebase]
    H -->|Fail| J[❌ Deployment Blocked]
Loading

Prettier Configuration

Configuration File

File: .prettierrc

{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "arrowParens": "always",
  "bracketSpacing": true,
  "endOfLine": "lf",
  "jsxSingleQuote": false,
  "bracketSameLine": false
}

Configuration Explained

Option Value Description
semi true Add semicolons at the end of statements
trailingComma "es5" Add trailing commas where valid in ES5
singleQuote true Use single quotes instead of double quotes
printWidth 80 Wrap lines at 80 characters
tabWidth 2 Use 2 spaces for indentation
useTabs false Use spaces instead of tabs
arrowParens "always" Always include parentheses around arrow function parameters
bracketSpacing true Add spaces inside object literals
endOfLine "lf" Use LF line endings (Unix-style)
jsxSingleQuote false Use double quotes in JSX
bracketSameLine false Put closing bracket on new line in JSX

Prettier Ignore

File: .prettierignore

# Dependencies
node_modules
package-lock.json

# Build outputs
dist
build
.vite

# Firebase
.firebase
.firebaserc
firebase-debug.log
firestore-debug.log

# Environment files
.env
.env.local
.env.production

# Logs
*.log

# Misc
*.min.js
*.min.css

Available Scripts

Format Code

# Auto-format all files
npm run format

# Check if files are formatted (no changes)
npm run format:check

Lint Code

# Run ESLint
npm run lint

Usage Examples

Before Committing

Always format and lint your code before committing:

# Format all files
npm run format

# Check for lint errors
npm run lint

# If all good, commit
git add .
git commit -m "feat: add new feature"

Check Without Modifying

To check if your code is properly formatted without making changes:

npm run format:check

This is useful in CI/CD pipelines.


Code Style Examples

Good Examples

JavaScript/JSX

// ✅ Good: Single quotes, semicolons, proper spacing
import React from 'react';
import { useState } from 'react';

const MyComponent = ({ title, description }) => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h1>{title}</h1>
      <p>{description}</p>
      <button onClick={handleClick}>Count: {count}</button>
    </div>
  );
};

export default MyComponent;

Object and Array Formatting

// ✅ Good: Proper spacing and trailing commas
const user = {
  name: 'John Doe',
  age: 30,
  email: 'john@example.com',
};

const colors = ['red', 'green', 'blue'];

const nestedObject = {
  level1: {
    level2: {
      value: 'deep',
    },
  },
};

Arrow Functions

// ✅ Good: Always use parentheses
const add = (a, b) => a + b;
const square = (x) => x * x;
const log = (message) => console.log(message);

Bad Examples (Will Be Auto-Fixed)

// ❌ Bad: Double quotes, no semicolons, inconsistent spacing
import React from "react"
import {useState} from "react"

const MyComponent = ({title,description}) => {
  const [count,setCount] = useState(0)

  const handleClick = () => {
    setCount(count+1)
  }

  return (
    <div>
      <h1>{ title }</h1>
      <p>{ description }</p>
      <button onClick={ handleClick }>Count: { count }</button>
    </div>
  )
}

export default MyComponent

Prettier will automatically fix these issues when you run npm run format.


ESLint Rules

This project uses ESLint for code quality. Key rules:

  • React Hooks Rules: Enforces rules of hooks
  • React Refresh: Ensures components can be refreshed
  • Unused Variables: Variables starting with _ or uppercase are ignored

ESLint Configuration

File: eslint.config.js

import js from '@eslint/js';
import globals from 'globals';
import react from 'eslint-plugin-react';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';

export default [
  { ignores: ['dist'] },
  {
    files: ['**/*.{js,jsx}'],
    languageOptions: {
      ecmaVersion: 2020,
      globals: globals.browser,
      parserOptions: {
        ecmaVersion: 'latest',
        ecmaFeatures: { jsx: true },
        sourceType: 'module',
      },
    },
    settings: { react: { version: '18.3' } },
    plugins: {
      react,
      'react-hooks': reactHooks,
      'react-refresh': reactRefresh,
    },
    rules: {
      ...js.configs.recommended.rules,
      ...react.configs.recommended.rules,
      ...react.configs['jsx-runtime'].rules,
      ...reactHooks.configs.recommended.rules,
      'react/jsx-no-target-blank': 'off',
      'react-refresh/only-export-components': [
        'warn',
        { allowConstantExport: true },
      ],
      'no-unused-vars': [
        'error',
        {
          argsIgnorePattern: '^_',
          varsIgnorePattern: '^_|^[A-Z]',
        },
      ],
    },
  },
];

CI/CD Integration

Automated Checks

When you push to the main branch, GitHub Actions will:

  1. Check Formatting - npm run format:check
  2. Run Linter - npm run lint
  3. Build Project - npm run build
  4. Deploy - Only if all checks pass
flowchart TD
    A[Push to main] --> B{Format Check}
    B -->|Pass| C{Lint Check}
    B -->|Fail| D[❌ Block Deployment]
    C -->|Pass| E[Build Project]
    C -->|Fail| D
    E -->|Success| F[Deploy to Firebase]
    E -->|Fail| D
Loading

Fixing CI/CD Failures

If your deployment fails due to format or lint errors:

# 1. Pull latest changes
git pull

# 2. Fix formatting
npm run format

# 3. Fix lint errors
npm run lint

# 4. Commit and push
git add .
git commit -m "fix: format and lint errors"
git push

Editor Integration

VS Code

Install the Prettier extension for automatic formatting on save:

  1. Install Prettier - Code formatter extension
  2. Add to .vscode/settings.json:
{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

WebStorm / IntelliJ

  1. Go to SettingsLanguages & FrameworksJavaScriptPrettier
  2. Enable On save
  3. Set Prettier package path

Sublime Text

Install JsPrettier package via Package Control.


Best Practices

1. Format Before Committing

Always run npm run format before committing code.

2. Use Editor Integration

Set up your editor to format on save for seamless formatting.

3. Review Changes

After formatting, review the changes to understand what was modified.

4. Don't Disable Rules

Avoid disabling Prettier or ESLint rules unless absolutely necessary.

5. Consistent Line Endings

Ensure your editor is set to use LF (Unix) line endings, not CRLF (Windows).


Troubleshooting

Format Check Fails in CI/CD

Problem: npm run format:check fails in GitHub Actions

Solution:

# Run locally to see what needs formatting
npm run format:check

# Fix all formatting issues
npm run format

# Commit the changes
git add .
git commit -m "fix: format code"
git push

Prettier Conflicts with ESLint

Problem: Prettier and ESLint give conflicting suggestions

Solution: Prettier handles formatting, ESLint handles code quality. This project is configured to avoid conflicts. If you encounter issues:

  1. Run Prettier first: npm run format
  2. Then run ESLint: npm run lint

Files Not Being Formatted

Problem: Some files aren't being formatted

Solution: Check .prettierignore to ensure files aren't excluded.

Line Ending Issues (Windows)

Problem: CRLF vs LF line ending conflicts

Solution:

# Configure Git to use LF
git config --global core.autocrlf input

# Re-format all files
npm run format

Code Style Summary

Aspect Tool Command
Formatting Prettier npm run format
Format Check Prettier npm run format:check
Linting ESLint npm run lint
Auto-fix Lint ESLint npm run lint -- --fix

Related Documentation


Next: GitHub Actions

📖 Documentation

Getting Started

Configuration

Advanced Topics

Deployment


🔗 Quick Links


⚡ Tech Stack

  • React 19
  • Vite
  • Firebase 12
  • Redux Toolkit
  • React Router
Clone this wiki locally