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

What configuration file formats does Prettier support and how to configure it?

2月21日 16:56

Prettier Configuration Files Explained

Prettier supports multiple configuration file formats, and developers can choose the appropriate configuration method based on project needs.

Configuration File Types

  1. .prettierrc - JSON format configuration file

    json
    { "semi": true, "singleQuote": true, "tabWidth": 2, "trailingComma": "es5" }
  2. .prettierrc.json - Explicit JSON format

    json
    { "printWidth": 80, "tabWidth": 2, "useTabs": false }
  3. .prettierrc.js - JavaScript format, supports dynamic configuration

    javascript
    module.exports = { semi: true, singleQuote: true, tabWidth: 2, };
  4. .prettierrc.cjs - CommonJS format

    javascript
    module.exports = { semi: true, singleQuote: true, };
  5. prettier.config.js - Configuration file in project root

    javascript
    export default { semi: true, singleQuote: true, };
  6. package.json - Configure in package.json

    json
    { "prettier": { "semi": true, "singleQuote": true } }

Common Configuration Options

  • printWidth: Specify line width, default 80
  • tabWidth: Specify indentation spaces, default 2
  • useTabs: Whether to use tab indentation, default false
  • semi: Whether to add semicolons at end of statements, default true
  • singleQuote: Whether to use single quotes, default false
  • trailingComma: Whether to add trailing commas, options "es5", "none", "all"
  • bracketSpacing: Whether to add spaces in object literal brackets, default true
  • arrowParens: Whether to use parentheses for arrow function parameters, options "always", "avoid"

Configuration Priority

Prettier looks for configuration files in the following order:

  1. prettier field in package.json
  2. .prettierrc (JSON/YAML)
  3. .prettierrc.json
  4. .prettierrc.yaml
  5. .prettierrc.yml
  6. .prettierrc.js
  7. .prettierrc.cjs
  8. prettier.config.js
  9. prettier.config.cjs

Ignore Configuration

Create a .prettierignore file to specify files or directories that don't need formatting:

shell
node_modules dist build *.min.js

Proper Prettier configuration keeps team code style consistent, improving code readability and maintainability.

标签:Prettier