Implementing Consistent Code Formatting with Prettier in JavaScript Projects

Best practices for using Prettier to enforce consistent code formatting and improve readability in JavaScript applications.

0 likes
7 views

Rule Content

---
title: Implementing Consistent Code Formatting with Prettier in JavaScript Projects
description: Best practices for using Prettier to enforce consistent code formatting and improve readability in JavaScript applications.
category: JavaScript Cursor Rules
---

# Implementing Consistent Code Formatting with Prettier in JavaScript Projects

## Context
- Applicable to all JavaScript projects to maintain consistent code style and enhance readability.
- Requires the installation of Prettier and its integration into the development workflow.

## Requirements
- **Prettier Configuration**: Create a `.prettierrc` file in the project root with the following settings:
  ```json
  {
    "trailingComma": "all",
    "tabWidth": 2,
    "semi": true,
    "singleQuote": true,
    "jsxSingleQuote": true,
    "printWidth": 80
  }
  ```
- **Editor Integration**: Configure the code editor to format code on save. For Visual Studio Code, add the following settings:
  ```json
  {
    "editor.formatOnSave": true,
    "prettier.enable": true
  }
  ```
- **Indentation and Line Length**:
  - Use 2 spaces for indentation.
  - Wrap lines after 80 characters to enhance readability.
- **Consistent Formatting**: Ensure all team members use the same Prettier configuration to maintain uniform code style across the codebase.

## Examples

<example>
**Good Example**: Properly formatted JavaScript code adhering to Prettier settings.
function greet(name) {
  console.log(`Hello, ${name}!`);
}
</example>

<example type="invalid">
**Bad Example**: Inconsistent indentation and line length exceeding 80 characters.
function greet(name) { console.log(`Hello, ${name}! Welcome to our platform. We hope you have a great experience.`); }
</example>