> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nativedesktop.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Format Project

> Automatically format your code with Prettier in your Native Desktop project

The `fmt` command runs Prettier on your Native Desktop project to automatically format your code, ensuring consistent style and formatting across your entire codebase.

## Prerequisites

Before running the format command, ensure:

* Your project has been created using `native-desktop create`
* All dependencies are installed (`npm install`)
* Prettier configuration exists (`.prettierrc`)

## Basic Usage

To format your project, open the terminal in the **root directory** of your Native Desktop project and run:

```shellscript theme={null}
native-desktop fmt
```

This command will:

1. Load Prettier configuration from `.prettierrc`
2. Scan all source files in your project
3. Automatically format files according to configured rules
4. Save the formatted files
5. Report the number of files formatted

## What Gets Formatted

By default, the format command processes:

* All TypeScript files (`.ts`, `.tsx`)
* All JavaScript files (`.js`, `.jsx`)
* JSON files (`.json`, `.json5`)
* Markdown files (`.md`, `.mdx`)
* CSS/SCSS files (`.css`, `.scss`)
* HTML files (`.html`)
* YAML files (`.yml`, `.yaml`)

Files and directories specified in `.prettierignore` are automatically excluded from formatting.

## Output Examples

### Successful Format

```shellscript theme={null}
$ native-desktop fmt

✓ Formatting complete
✓ 24 files formatted
✓ 0 files unchanged
All files are now properly formatted
```

### No Changes Needed

```shellscript theme={null}
$ native-desktop fmt

✓ All files already formatted
✓ 0 files changed
✓ 24 files checked
No formatting changes needed
```

### With Errors

```shellscript theme={null}
$ native-desktop fmt

✖ Error formatting files
✖ Syntax error in src/index.ts
Please fix syntax errors before formatting
```

## Prettier Configuration

The format command uses the `.prettierrc` file generated by `native-desktop create`. Here's an example configuration:

```json theme={null}
{
  "semi": true,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "arrowParens": "always",
  "endOfLine": "lf"
}
```

## Configuration Options

Common Prettier options you can customize:

<Tabs>
  <Tab title="Code Style">
    * **semi**: Add semicolons at the end of statements (default: `true`)
    * **singleQuote**: Use single quotes instead of double quotes (default: `true`)
    * **quoteProps**: When to quote properties in objects
    * **jsxSingleQuote**: Use single quotes in JSX (default: `false`)
  </Tab>

  <Tab title="Spacing">
    * **tabWidth**: Number of spaces per indentation level (default: `2`)
    * **useTabs**: Use tabs instead of spaces (default: `false`)
    * **printWidth**: Maximum line length (default: `80`)
  </Tab>

  <Tab title="Trailing Items">
    * **trailingComma**: Add trailing commas where valid (options: `"none"`, `"es5"`, `"all"`)
    * **bracketSpacing**: Print spaces between brackets in object literals (default: `true`)
    * **bracketSameLine**: Put `>` on the same line in JSX (default: `false`)
  </Tab>

  <Tab title="Special">
    * **arrowParens**: Include parentheses around arrow function parameters (options: `"always"`, `"avoid"`)
    * **endOfLine**: Line ending style (options: `"lf"`, `"crlf"`, `"cr"`, `"auto"`)
    * **proseWrap**: How to wrap prose in Markdown (options: `"always"`, `"never"`, `"preserve"`)
  </Tab>
</Tabs>

## Formatting Examples

### Before Formatting

```typescript theme={null}
const myFunction=(x:number,y:number)=>{
return x+y
}

const obj={name:"John",age:30,city:"New York"}

if(condition){
console.log("Hello")
}
```

### After Formatting

```typescript theme={null}
const myFunction = (x: number, y: number) => {
  return x + y;
};

const obj = { name: 'John', age: 30, city: 'New York' };

if (condition) {
  console.log('Hello');
}
```

## Ignoring Files

Create or edit `.prettierignore` to exclude files from formatting:

```
# .prettierignore
node_modules/
bin/
dist/
build/
coverage/
*.min.js
*.bundle.js
package-lock.json
```

## Ignoring Code Blocks

You can ignore specific code blocks in your files:

```typescript theme={null}
// prettier-ignore
const uglyMatrix = [
  1,0,0,
  0,1,0,
  0,0,1
];

// This will be formatted normally
const normalArray = [1, 2, 3, 4, 5];
```

Or ignore entire files:

```typescript theme={null}
// prettier-ignore-file

// This entire file won't be formatted
const anything = "goes here"
```

## Integration with Development Workflow

### Pre-Commit Hook

Format code automatically before commits using Husky:

```json theme={null}
{
  "husky": {
    "hooks": {
      "pre-commit": "native-desktop fmt"
    }
  }
}
```

### CI/CD Pipeline

Check formatting in your continuous integration:

```yaml theme={null}
# GitHub Actions example
- name: Check Code Formatting
  run: |
    native-desktop fmt
    git diff --exit-code
```

### npm Scripts

Add formatting to your package.json scripts:

```json theme={null}
{
  "scripts": {
    "format": "native-desktop fmt",
    "format:check": "prettier --check .",
    "precommit": "native-desktop fmt && native-desktop lint"
  }
}
```

## Format vs Lint

Understanding the difference between `fmt` and `lint`:

| Aspect        | `native-desktop fmt`         | `native-desktop lint`         |
| ------------- | ---------------------------- | ----------------------------- |
| **Purpose**   | Code formatting              | Code quality & patterns       |
| **Tool**      | Prettier                     | ESLint                        |
| **Auto-Fix**  | ✅ Yes (always)               | ⚠️ Limited                    |
| **Focus**     | Style consistency            | Logic & best practices        |
| **Concerns**  | Indentation, quotes, spacing | Unused variables, type safety |
| **Conflicts** | Can conflict with ESLint     | Can conflict with Prettier    |

<Tip>
  Use both commands together: `native-desktop fmt` for style, `native-desktop lint` for quality.
</Tip>

## Common Issues

<AccordionGroup>
  <Accordion title="Prettier Configuration Not Found">
    **Error**: `.prettierrc not found`

    **Solution**: Ensure the configuration file exists in your project root.

    ```shellscript theme={null}
    # Check if file exists
    ls -la .prettierrc

    # Create default configuration if missing
    echo '{ "semi": true, "singleQuote": true }' > .prettierrc
    ```
  </Accordion>

  <Accordion title="Syntax Errors Prevent Formatting">
    **Error**: `SyntaxError: Unexpected token`

    **Solution**: Fix syntax errors in your code before formatting.

    ```shellscript theme={null}
    # Check for TypeScript errors
    native-desktop types

    # Fix syntax errors, then format
    native-desktop fmt
    ```
  </Accordion>

  <Accordion title="Conflicting ESLint and Prettier Rules">
    **Error**: ESLint and Prettier disagree on formatting

    **Solution**: Install `eslint-config-prettier` to disable conflicting ESLint rules.

    ```shellscript theme={null}
    npm install --save-dev eslint-config-prettier
    ```

    Update `.eslintrc.json`:

    ```json theme={null}
    {
      "extends": [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended",
        "prettier"
      ]
    }
    ```
  </Accordion>

  <Accordion title="Files Not Being Formatted">
    **Error**: Some files are not formatted

    **Solution**: Check `.prettierignore` and ensure files aren't excluded.

    ```shellscript theme={null}
    # List files that would be formatted
    npx prettier --list-different "src/**/*.ts"

    # Check ignore patterns
    cat .prettierignore
    ```
  </Accordion>

  <Accordion title="Format Changes Not Saved">
    **Error**: Files appear formatted but changes aren't saved

    **Solution**: Check file permissions and ensure you have write access.

    ```shellscript theme={null}
    # Check file permissions
    ls -la src/

    # Fix permissions if needed
    chmod u+w src/*.ts
    ```
  </Accordion>
</AccordionGroup>

## Customizing Prettier

You can customize Prettier rules in `.prettierrc`:

```json theme={null}
{
  // Use single quotes
  "singleQuote": true,
  
  // Always add semicolons
  "semi": true,
  
  // Add trailing commas
  "trailingComma": "all",
  
  // 100 characters per line
  "printWidth": 100,
  
  // 2 spaces for indentation
  "tabWidth": 2,
  
  // Use spaces, not tabs
  "useTabs": false,
  
  // Always wrap arrow function parameters
  "arrowParens": "always",
  
  // Unix line endings
  "endOfLine": "lf",
  
  // Add space between brackets
  "bracketSpacing": true
}
```

## Language-Specific Overrides

You can apply different rules to different file types:

```json theme={null}
{
  "semi": true,
  "singleQuote": true,
  "overrides": [
    {
      "files": "*.json",
      "options": {
        "printWidth": 120
      }
    },
    {
      "files": "*.md",
      "options": {
        "proseWrap": "always",
        "printWidth": 80
      }
    },
    {
      "files": "*.html",
      "options": {
        "printWidth": 120,
        "htmlWhitespaceSensitivity": "ignore"
      }
    }
  ]
}
```

## IDE Integration

### Visual Studio Code

Install the Prettier extension:

1. Open VS Code
2. Go to Extensions (Cmd+Shift+X / Ctrl+Shift+X)
3. Search for "Prettier - Code formatter"
4. Install the official Prettier extension

Configure auto-format on save:

```json theme={null}
{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.formatOnPaste": true,
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}
```

### WebStorm / IntelliJ IDEA

Prettier is built-in. Enable it in:

**Settings → Languages & Frameworks → JavaScript → Prettier**

* Check "Automatic Prettier configuration"
* Check "Run on save for files"

### Sublime Text

Install the JsPrettier package via Package Control.

## Best Practices

<CardGroup cols={2}>
  <Card title="Format Frequently" icon="clock">
    Run formatting regularly during development to maintain consistency.
  </Card>

  <Card title="Commit Formatted Code" icon="code-commit">
    Always format code before committing to keep the repository clean.
  </Card>

  <Card title="Team Consistency" icon="users">
    Share the same Prettier configuration across your entire team.
  </Card>

  <Card title="Automate Formatting" icon="wand-magic-sparkles">
    Set up automatic formatting in your IDE and CI/CD pipeline.
  </Card>
</CardGroup>

## Checking Without Formatting

To check if files need formatting without modifying them:

```shellscript theme={null}
# Using Prettier directly
npx prettier --check .

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

This is useful for CI/CD pipelines where you want to verify formatting without making changes.

## Format Specific Files

While the CLI command formats the entire project, you can format specific files using npx:

```shellscript theme={null}
# Format specific file
npx prettier --write src/index.ts

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

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

## Development Workflow

Recommended workflow for code formatting:

```mermaid theme={null}
graph LR
    A[Write Code] --> B[Save File]
    B --> C[Auto-Format on Save]
    C --> D[Continue Coding]
    D --> E[Before Commit]
    E --> F[native-desktop fmt]
    F --> G[native-desktop lint]
    G --> H[Commit]
```

## Performance Tips

<CardGroup cols={2}>
  <Card title="Use .prettierignore" icon="ban">
    Exclude large directories to speed up formatting.
  </Card>

  <Card title="Format Changed Files" icon="filter">
    In large projects, format only modified files.
  </Card>

  <Card title="Cache Results" icon="database">
    Prettier caches results for faster subsequent runs.
  </Card>

  <Card title="IDE Formatting" icon="keyboard">
    Use IDE auto-format for immediate feedback.
  </Card>
</CardGroup>

## Command Comparison

| Command                | Tool       | Purpose            | Changes Files |
| ---------------------- | ---------- | ------------------ | ------------- |
| `native-desktop fmt`   | Prettier   | Format code style  | ✅ Yes         |
| `native-desktop lint`  | ESLint     | Check code quality | ❌ No          |
| `native-desktop types` | TypeScript | Check types        | ❌ No          |

<Info>
  For best results, run all three commands as part of your development workflow.
</Info>

## Exit Codes

The format command uses standard exit codes:

* **0**: Files formatted successfully
* **1**: Errors occurred during formatting

```shellscript theme={null}
native-desktop fmt
echo $?  # Check exit code
```
