Skip to content

Prettier Configuration

Complete guide to Prettier code formatting configuration in the TypeScript Project Template.

Overview

The template uses Prettier for consistent code formatting with:

  • Single quotes for strings
  • No trailing commas for clean syntax
  • 2-space indentation for readability
  • 100-character line width for modern displays
  • Semicolons enabled for explicit statements

Configuration File (.prettierrc.json)

Basic Configuration

json
{
  "semi": true,
  "trailingComma": "none",
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "bracketSpacing": true,
  "bracketSameLine": false,
  "arrowParens": "always",
  "endOfLine": "lf"
}

Configuration Options Explained

String Formatting

typescript
// singleQuote: true
const message = 'Hello World';
const template = `Template string with ${variable}`;

// singleQuote: false (not used)
const message = "Hello World";

Trailing Commas

typescript
// trailingComma: "none"
const config = {
  debug: true,
  timeout: 5000,
  retries: 3
};

const array = [
  'item1',
  'item2',
  'item3'
];

// trailingComma: "all" (not used)
const config = {
  debug: true,
  timeout: 5000,
  retries: 3,
};

Line Width and Indentation

typescript
// printWidth: 100, tabWidth: 2
function processLongFunctionNameWithManyParameters(
  firstParameter: string,
  secondParameter: number,
  thirdParameter: boolean
): Promise<void> {
  // Function body with 2-space indentation
  if (firstParameter && secondParameter > 0) {
    console.log('Processing with parameters');
  }
}

Bracket Spacing

typescript
// bracketSpacing: true
const config = { debug: true, timeout: 5000 };

// bracketSpacing: false (not used)
const config = {debug: true, timeout: 5000};

Arrow Function Parentheses

typescript
// arrowParens: "always"
const single = (x) => x * 2;
const multiple = (x, y) => x + y;

// arrowParens: "avoid" (not used)
const single = x => x * 2;
const multiple = (x, y) => x + y;

Running Prettier

Basic Commands

bash
# Check formatting
npm run format:check

# Apply formatting
npm run format

# Format specific files
npx prettier --write "src/**/*.ts"

# Check specific files
npx prettier --check "src/**/*.ts"

File Patterns

bash
# Format TypeScript files
npx prettier --write "**/*.ts"

# Format JavaScript files
npx prettier --write "**/*.js"

# Format JSON files
npx prettier --write "**/*.json"

# Format Markdown files
npx prettier --write "**/*.md"

IDE Integration

VS Code Settings

json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "prettier.configPath": ".prettierrc.json",
  "prettier.requireConfig": true
}

VS Code Workspace Settings

json
{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "editor.formatOnSave": true,
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

Ignore Files (.prettierignore)

Basic Ignore Patterns

# Build outputs
dist/
build/
coverage/

# Dependencies
node_modules/

# Generated files
*.min.js
*.bundle.js

# Documentation builds
docs/.vitepress/dist/
docs/api/generated/

# Configuration files that should maintain specific formatting
package-lock.json
yarn.lock

Advanced Ignore Patterns

# Ignore specific file types
*.svg
*.png
*.jpg

# Ignore specific directories
temp/
.cache/
.next/

# Ignore files with specific patterns
**/generated/**
**/*.generated.*

Integration with ESLint

ESLint Configuration

javascript
// eslint.config.js
import prettierPlugin from 'eslint-plugin-prettier';

export default [
  {
    plugins: {
      prettier: prettierPlugin
    },
    rules: {
      'prettier/prettier': 'error'
    }
  }
];

Resolving Conflicts

javascript
// Disable ESLint rules that conflict with Prettier
export default [
  {
    rules: {
      // Disable formatting rules handled by Prettier
      'indent': 'off',
      'linebreak-style': 'off',
      'quotes': 'off',
      'semi': 'off',
      '@typescript-eslint/indent': 'off'
    }
  }
];

Customization Examples

Project-Specific Overrides

json
{
  "semi": true,
  "trailingComma": "none",
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 2,
  "overrides": [
    {
      "files": "*.md",
      "options": {
        "printWidth": 80,
        "proseWrap": "always"
      }
    },
    {
      "files": "*.json",
      "options": {
        "tabWidth": 4
      }
    }
  ]
}

Language-Specific Configuration

json
{
  "overrides": [
    {
      "files": "*.ts",
      "options": {
        "parser": "typescript"
      }
    },
    {
      "files": "*.js",
      "options": {
        "parser": "babel"
      }
    },
    {
      "files": "*.json",
      "options": {
        "parser": "json"
      }
    }
  ]
}

Pre-commit Integration

Husky + lint-staged Setup

json
{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{ts,js,json,md}": [
      "prettier --write",
      "git add"
    ]
  }
}

Manual Pre-commit Check

bash
#!/bin/bash
# pre-commit hook

# Check formatting
npm run format:check
if [ $? -ne 0 ]; then
  echo "❌ Code formatting issues found. Run 'npm run format' to fix."
  exit 1
fi

echo "✅ Code formatting is correct."

Formatting Examples

Before and After

TypeScript Interface

typescript
// Before formatting
interface   UtilConfig{debug?:boolean;maxRetries?:number;timeout?:number;}

// After formatting
interface UtilConfig {
  debug?: boolean;
  maxRetries?: number;
  timeout?: number;
}

Function Declaration

typescript
// Before formatting
export async function formatTimestamp(timestamp:number,config:UtilConfig={}):string{
if(config.debug){console.log(`Formatting timestamp ${timestamp}`);}
return new Date(timestamp).toISOString().replace('T',' ').substring(0,19);
}

// After formatting
export async function formatTimestamp(
  timestamp: number,
  config: UtilConfig = {}
): string {
  if (config.debug) {
    console.log(`Formatting timestamp ${timestamp}`);
  }
  return new Date(timestamp).toISOString().replace('T', ' ').substring(0, 19);
}

Object and Array Formatting

typescript
// Before formatting
const config={debug:true,maxRetries:3,timeout:5000,};
const items=['item1','item2','item3',];

// After formatting
const config = {
  debug: true,
  maxRetries: 3,
  timeout: 5000
};
const items = ['item1', 'item2', 'item3'];

Troubleshooting

Common Issues

Configuration Not Found

bash
# Error: No configuration found
# Solution: Ensure .prettierrc.json exists in project root
ls -la .prettierrc.json

# Or specify config path
npx prettier --config .prettierrc.json --write "src/**/*.ts"

Conflicting Rules with ESLint

bash
# Error: ESLint and Prettier rules conflict
# Solution: Use eslint-config-prettier to disable conflicting rules
npm install --save-dev eslint-config-prettier

IDE Not Formatting

json
// VS Code settings.json
{
  "editor.formatOnSave": true,
  "prettier.requireConfig": true,
  "prettier.configPath": ".prettierrc.json"
}

Performance Issues

bash
# Large file formatting is slow
# Solution: Use ignore patterns for large generated files
echo "dist/" >> .prettierignore
echo "coverage/" >> .prettierignore

Best Practices

Configuration Management

  • Use consistent configuration across team
  • Document formatting decisions and rationale
  • Version control configuration files
  • Regular review of formatting rules

Team Adoption

  • Set up IDE integration for all team members
  • Use pre-commit hooks to enforce formatting
  • Include formatting in CI/CD pipeline
  • Provide clear documentation for new team members

Maintenance

  • Regular updates to Prettier version
  • Review configuration for new language features
  • Monitor performance on large codebases
  • Adjust rules based on team feedback

Integration Strategy

  • Combine with ESLint for comprehensive code quality
  • Use with TypeScript for type-safe formatting
  • Integrate with Git hooks for automatic enforcement
  • Include in CI/CD for consistent formatting across environments

Released under the MIT License.