Prettier实现保存自动格式化

一、概述

Prettier 是一个代码格式化工具,支持 JavaScript、TypeScript、HTML、CSS、JSON、Markdown 等多种语言,能自动统一代码风格,减少团队成员间的格式争议。

在 VS Code 中配置 Prettier 后,保存文件时即可自动格式化,无需手动调整。

二、VS Code 环境配置

1. 安装 Prettier 插件

在 VS Code 扩展市场搜索 Prettier - Code formatter(发布者 esbenp)并安装。

2. 项目安装 Prettier 依赖

复制代码
npm install --save-dev prettier

3. 配置 settings.json

将以下内容添加到 .vscode/settings.json

复制代码
{
  "prettier.prettierPath": "./node_modules/prettier",
  "prettier.requireConfig": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "files.autoSave": "onFocusChange",
  "editor.formatOnSave": true
}

各配置项说明:

配置项 作用
prettier.prettierPath 指定 Prettier 路径,使用项目本地安装的版本,避免全局版本不一致
prettier.requireConfig 要求项目根目录存在 .prettierrc 配置文件,防止未配置的项目误格式化
editor.defaultFormatter 指定默认格式化工具为 Prettier,避免与其他格式化插件冲突
files.autoSave onFocusChange 表示编辑器失去焦点时自动保存
editor.formatOnSave 保存文件时自动执行格式化

三、.prettierrc 规则详解

在项目根目录创建 .prettierrc.prettierrc.json 文件来自定义格式化规则。

完整配置示例:

复制代码
{
    "printWidth": 80,
    "tabWidth": 2,
    "useTabs": false,
    "semi": true,
    "singleQuote": true,
    "trailingComma": "none",
    "bracketSpacing": true,
    "jsxBracketSameLine": false,
    "arrowParens": "avoid",
    "proseWrap": "preserve",
    "htmlWhitespaceSensitivity": "css",
    "endOfLine": "auto"
}

基础格式

printWidth(默认 80)

每行代码的最大字符数。超过该长度,Prettier 会自动换行。

复制代码
// 超过 80 字符,格式化后自动换行
const result = someLongFunction(param1, param2, param3, param4, param5);

// 换行后
const result = someLongFunction(
  param1,
  param2,
  param3,
  param4,
  param5
);
tabWidth(默认 2)

每个缩进级别使用的空格数。

复制代码
function hello() {
  console.log("Hello"); // 2 空格缩进
  if (true) {
    console.log("World"); // 4 空格缩进(2 级)
  }
}
useTabs(默认 false)

是否使用 Tab 字符代替空格。设为 false 使用空格(推荐),设为 true 使用 Tab。

代码风格

semi(默认 true)

是否在语句末尾添加分号。

复制代码
// true:加分号
const name = "John";

// false:不加分号
const name = "John"
singleQuote(默认 false)

是否使用单引号。注意:JSX 属性始终使用双引号,不受此项影响。

复制代码
// true:单引号
const name = 'John';
import React from 'react';

// JSX 属性始终双引号
<div className="container">Hello</div>
trailingComma(默认 "all")

多行结构末尾是否添加逗号。

说明
"none" 不添加尾逗号
"es5" 仅在数组、对象中添加(ES5 兼容)
"all" 所有地方都添加(包括函数参数),推荐,减少 git diff 冲突
复制代码
// "all":末尾有逗号
const user = {
  name: 'John',
  age: 18,
};

// "none":末尾无逗号
const user = {
  name: 'John',
  age: 18
};
bracketSpacing(默认 true)

对象字面量括号内是否添加空格。

复制代码
// true:有空格
const obj = { name: 'John' };

// false:无空格
const obj = {name: 'John'};
arrowParens(默认 "always")

箭头函数的单个参数是否添加括号。

复制代码
// "avoid":省略括号
const fn = x => x * 2;

// "always":总是有括号
const fn = (x) => x * 2;
jsxBracketSameLine(默认 false)

JSX 标签的 > 是否与属性放在同一行末尾。

复制代码
// false:> 另起一行(推荐)
<button
  className="btn"
  onClick={handleClick}
>
  点击
</button>

// true:> 在同一行
<button
  className="btn"
  onClick={handleClick}>
  点击
</button>

其他

proseWrap(默认 "preserve")

Markdown 文本的换行处理方式。"preserve" 保持原样,"always" 始终换行,"never" 永不换行。

htmlWhitespaceSensitivity(默认 "css")

HTML 文件中空格的处理敏感度。"css" 遵循 CSS display 规则,"strict" 严格保留,"ignore" 忽略。

endOfLine(默认 "lf")

文件末尾换行符格式。"auto" 自动检测(推荐跨平台项目),"lf" 为 Unix 风格,"crlf" 为 Windows 风格。

四、格式化效果对比

格式化前(凌乱):

复制代码
import React,{useState,useEffect} from 'react';

function MyComponent(props){
const [count,setCount]=useState(0);
const handleClick=()=>{
setCount(c=>c+1);
}
return(
<div className="container">
  <button onClick={handleClick}>点击:{count}</button>
</div>
)
}

格式化后(整齐):

复制代码
import React, { useState, useEffect } from 'react';

function MyComponent(props) {
  const [count, setCount] = useState(0);
  const handleClick = () => {
    setCount(c => c + 1);
  };
  return (
    <div className="container">
      <button onClick={handleClick}>点击:{count}</button>
    </div>
  );
}

五、常见配置风格参考

保守风格(争议少,适合大多数团队)

复制代码
{
  "printWidth": 80,
  "tabWidth": 2,
  "singleQuote": true,
  "trailingComma": "none",
  "arrowParens": "avoid"
}

Airbnb 风格

复制代码
{
  "printWidth": 100,
  "singleQuote": true,
  "trailingComma": "all",
  "arrowParens": "always"
}

Google 风格

复制代码
{
  "printWidth": 80,
  "tabWidth": 2,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "none"
}

六、快速上手步骤

  1. 安装依赖npm install --save-dev prettier

  2. 创建配置文件 :在项目根目录创建 .prettierrc,填入格式化规则

  3. 配置 VS Code :在 .vscode/settings.json 中启用保存自动格式化

  4. 添加 npm 脚本(可选):

    {
    "scripts": {
    "format": "prettier --write .",
    "format:check": "prettier --check ."
    }
    }

  5. 统一 lock 文件 :团队开发时确保所有人使用相同配置,将 .prettierrc 提交到 Git

七、常见问题

Q1: 保存时不自动格式化?

检查三项:

  • 是否安装了 Prettier VS Code 插件
  • editor.formatOnSave 是否为 true
  • 项目根目录是否配置了 .prettierrc(当 requireConfigtrue 时)

Q2: Prettier 和 ESLint 冲突怎么办?

ESLint 负责代码质量(如未使用变量),Prettier 负责格式。冲突时安装 eslint-config-prettier 关闭 ESLint 中与格式相关的规则:

复制代码
npm install --save-dev eslint-config-prettier

Q3: 团队用不同系统(Win/Mac/Linux)有问题吗?

endOfLine 设为 "auto" 可自动适配各系统的换行符,避免协作时的 diff 噪音。

参考链接:VSCode配置Prettier插件实现保存时自动格式化代码-开发者社区-阿里云

相关推荐
垚森3 天前
我用 GLM-5.2 造了个炸裂主题后台:16 套主题随心切,可在线体验
ai·react
爱就是恒久忍耐13 天前
VSCode里如何比较2个branch
ide·vscode·编辑器
意法半导体STM3213 天前
【官方原创】如何为STM32CubeMX2配置Visual Studio Code配置方案
vscode·stm32·单片机·嵌入式硬件·策略模式·stm32cubemx·嵌入式开发
bloglin9999914 天前
vscode中可视化的合并分支,在“合并编辑器中解析”中“与基线进行比较”是什么意思
ide·vscode·编辑器
天疆说14 天前
在 Ubuntu 的 VSCode 中配置 MATLAB
vscode·ubuntu·matlab
春日见14 天前
vscode的AI编程插件推荐:
大数据·ide·vscode·算法·机器学习·编辑器·ai编程
jieshenai14 天前
VScode sys.path,并使CTRL+左键可访问源码
ide·vscode·编辑器
qq_4480111614 天前
VSCode环境搭建
ide·vscode·编辑器
qq_3384323714 天前
VSCode Remote-SSH 远程 Windows Server 卡死的排查与解决
windows·vscode·ssh
console.log('npc')15 天前
Codex 桌面端接入 Headroom 压缩代理完整教程
前端·vscode