Skip to content

Prettier 代码格式化工具

Prettier 是一个备受推崇的代码格式化工具,它能够自动将代码格式化为一致的样式规范。作为一个有主见的代码格式化器,Prettier 放弃了许多样式选择,以减少决策负担,让开发者专注于代码逻辑本身。

官方文档

GitHub 仓库

核心特性

  • 多语言支持:支持 JavaScript、TypeScript、CSS、HTML、JSON、YAML、Markdown、GraphQL 等多种语言
  • 零配置:内置合理的默认配置,开箱即用
  • 可定制化:通过配置文件进行自定义设置
  • 编辑器集成:支持 VS Code、Sublime Text、WebStorm 等主流编辑器
  • CLI 支持:可以通过命令行直接格式化代码
  • 与 ESLint 配合:与 ESLint 完美配合,实现代码检查和格式化的协同工作

安装方法

全局安装

bash
npm install -g prettier

或者

bash
yarn global add prettier

本地安装

bash
npm install --save-dev prettier

或者

bash
yarn add --dev prettier

基础使用

命令行格式化

bash
prettier --write example.js
prettier --write "src/**/*.js"
prettier --check src

检查文件格式

bash
prettier --check src/index.js

从标准输入读取

bash
echo "const  x=   1" | prettier --stdin-filepath test.js

格式化 JSON 文件

bash
prettier --write config.json

指定解析器

bash
prettier --write example.js --parser babel
prettier --write example.ts --parser typescript

配置文件

独立配置文件 .prettierrc

json
{
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "es5",
  "bracketSpacing": true,
  "endOfLine": "lf"
}

package.json 中配置

json
{
  "prettier": {
    "printWidth": 100,
    "tabWidth": 2,
    "singleQuote": true,
    "trailingComma": "es5"
  }
}

忽略文件 .prettierignore

dist/
build/
coverage/
node_modules/

配置选项

基本选项

选项默认值说明
printWidth80单行最大字符数
tabWidth2每个 tab 的空格数
useTabsfalse使用 tab 代替空格
semitrue语句结尾加分号
singleQuotefalse使用单引号
trailingComma"none"尾随逗号风格
bracketSpacingtrue对象字面量空格

样式选项

json
{
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "es5",
  "bracketSpacing": true,
  "parser": "babel",
  "htmlWhitespaceSensitivity": "css",
  "vueIndentScriptAndStyle": false,
  "quoteProps": "as-needed",
  "jsxSingleQuote": false,
  "jsxBracketSameLine": false,
  "arrowParens": "always",
  "endOfLine": "lf",
  "embeddedLanguageFormatting": "auto"
}

编辑器集成

VS Code

  1. 安装 Prettier 扩展
  2. 在设置中添加:
json
{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.formatOnPaste": false
}

WebStorm

  1. 安装 Prettier 插件
  2. 在 Settings > Tools > Prettier 中配置
  3. 启用 "Format on Save"

Vim/Neovim

使用 ALE 或 coc-prettier 插件

与 ESLint 集成

安装插件

bash
npm install --save-dev eslint-config-prettier eslint-plugin-prettier

ESLint 配置

javascript
module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:prettier/recommended'
  ],
  plugins: ['prettier'],
  rules: {
    'prettier/prettier': 'error'
  }
};

独立使用

javascript
module.exports = {
  extends: ['prettier'],
  rules: {
    'prettier/prettier': 'error'
  }
};

API 使用

作为模块使用

javascript
const prettier = require('prettier');

async function formatCode() {
  const code = 'const   x  =   1';
  const formatted = await prettier.format(code, {
    parser: 'babel',
    printWidth: 80,
    singleQuote: true
  });
  console.log(formatted);
}

formatCode();

使用解析器

javascript
const prettier = require('prettier');

async function formatWithParser() {
  const code = 'interface Props { name: string }';
  
  const result = await prettier.formatWithCursor(code, {
    parser: 'typescript',
    cursorOffset: 10
  });
  
  console.log(result.formatted);
}

formatWithParser();

忽略代码片段

使用注释忽略

javascript
// prettier-ignore
const x = {
  veryLongKey: 'veryLongValue',
  anotherVeryLongKey: 'anotherVeryLongValue'
};

JSX 忽略

jsx
{/* prettier-ignore */}
<div   className="container"
      id="main"
>
  Content
</div>

HTML 忽略

html
<!-- prettier-ignore -->
<div   class="container"
       id="main"
>
  Content
</div>

常见问题

配置文件不生效

确保配置文件在项目根目录,或使用 --config 参数指定路径:

bash
prettier --write src/index.js --config ./my-prettier-config.json

与 ESLint 冲突

安装 eslint-config-prettier 并添加到 ESLint 配置的 extends 中:

javascript
module.exports = {
  extends: ['eslint:recommended', 'prettier']
};

格式化 TypeScript 文件

使用 TypeScript 解析器:

bash
prettier --write src/index.ts --parser typescript

或在配置文件中:

json
{
  "parser": "typescript",
  "filepath": "**/*.ts"
}

处理大文件

对于非常大的文件,可以使用 grep 配合 xargs 进行并行处理:

bash
find src -name "*.js" | xargs -P 4 prettier --write

Vue 文件格式化

bash
prettier --write src/App.vue --parser vue

GraphQL 格式化

bash
prettier --write src/schema.graphql --parser graphql

Markdown 格式化

bash
prettier --write src/docs/*.md

YAML 格式化

bash
prettier --write config.yaml --parser yaml

TOML 格式化

bash
prettier --write Cargo.toml --parser toml

指定文件编码

bash
prettier --write src/index.js --editorconfig

使用 .editorconfig

Prettier 支持 .editorconfig,可以与项目现有的编辑器配置配合使用:

ini
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

最佳实践

  • 在 CI/CD 中运行 Prettier 检查,确保代码风格一致性
  • 使用 Git Hook 在提交前自动格式化代码
  • 将 Prettier 配置纳入版本控制,确保团队成员使用一致的配置
  • 定期更新 Prettier 以获得最新的格式化规则和语言支持
  • 对于大型项目,使用 .prettierignore 排除构建产物和第三方代码
  • 结合 ESLint 使用,同时进行代码检查和格式化
  • 在项目根目录运行 Prettier,确保使用正确的配置文件

高级用法

在 Git Hook 中使用

bash
npx mrm@2 lint-staged

配置 package.json

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

与 GitHub Actions 集成

yaml
name: Prettier

on: [push, pull_request]

jobs:
  prettier:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      - run: npm install
      - run: npx prettier --check .

在 npm scripts 中使用

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}\""
  }
}

使用 ignore-node-modules

bash
npx prettier --write "**/*.{js,jsx,ts,tsx,json,css,md}" --ignore-path .gitignore --ignore-node-modules

输出到指定目录

bash
prettier --write src/ --dist-dir dist

指定行范围

bash
prettier --write src/index.js --range-start 0 --range-end 100