乐闻世界logo
搜索文章和话题

What are the common commands and options for Prettier CLI tool?

2月21日 16:56

Prettier Command Line Tool Explained

Prettier provides a rich command line tool that can flexibly perform code formatting, checking, and configuration management.

Basic Commands

1. Format Files

bash
# Format a single file prettier --write index.js # Format multiple files prettier --write src/**/*.js # Format all supported files prettier --write .

2. Check File Format

bash
# Check if file format is correct prettier --check index.js # Check multiple files prettier --check "src/**/*.{js,jsx,ts,tsx}" # Check all files prettier --check .

3. View Formatting Differences

bash
# Show formatting differences prettier --diff index.js # List files that need formatting prettier --list-different "src/**/*.js"

Common Options

1. Configuration Related

bash
# Specify configuration file prettier --config .prettierrc.custom --write index.js # Specify ignore file prettier --ignore-path .prettierignore.custom --write . # Disable default ignore prettier --write --ignore-unknown index.js

2. Output Control

bash
# Output to stdout (don't modify file) prettier index.js # Specify output directory prettier --out-dir formatted src/**/*.js # Use cache prettier --write --cache "src/**/*.js" # Clear cache prettier --write --cache --cache-strategy content "src/**/*.js"

3. Debug Related

bash
# Show debug information prettier --debug-check index.js # Show used configuration prettier --find-config-path index.js # Show parser information prettier --help

Advanced Usage

1. Combine with Other Tools

bash
# Use with find find src -name "*.js" | xargs prettier --write # Use with git git diff --name-only --diff-filter=ACM | grep '\.js$' | xargs prettier --write

2. Format Specific File Types

bash
# Only format JavaScript files prettier --write "**/*.js" # Format multiple file types prettier --write "**/*.{js,jsx,ts,tsx,json,css,md}"

3. Run with npx

bash
# Run with npx (no global installation needed) npx prettier --write index.js # Run with specific version npx prettier@2.8.0 --write index.js

Useful Scripts

Add common scripts to package.json:

json
{ "scripts": { "format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"", "format:check": "prettier --check \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"", "format:staged": "lint-staged", "format:all": "prettier --write ." } }

Common Problem Solutions

1. File Encoding Issues

bash
# Specify file encoding prettier --write --encoding utf-8 index.js

2. Permission Issues

bash
# Run with sudo (not recommended) sudo prettier --write index.js

3. Performance Issues

bash
# Use cache to improve performance prettier --write --cache "**/*.js"

Mastering Prettier command line tools enables more efficient code formatting management.

标签:Prettier