Prettier负责代码格式化,ESLint负责检测问题,二者配合是主流前端代码规范方案;VSCode安装对应插件并配置.eslintrc.cjs、.prettierrc等文件,启用保存时自动修复即可实现统一风格与错误预防。

想让团队代码风格统一、减少低级错误?Prettier 负责格式化,ESLint 负责找问题,两者配合是目前最主流的前端代码规范方案。VSCode 里配好一次,写代码时自动修复,省心又专业。
安装必要插件和依赖
先确保 VSCode 已安装两个核心插件:
- Prettier(官方插件,ID:esbenp.prettier-vscode)
- ESLint(官方插件,ID:dbaeumer.vscode-eslint)
项目本地也需要装对应依赖,推荐使用 npm:
npm install --save-dev prettier eslint eslint-config-prettier eslint-plugin-react eslint-plugin-react-hooks
如果用 TypeScript,再加:eslint-plugin-import @typescript-eslint/eslint-plugin @typescript-eslint/parser
配置 ESLint 规则文件
在项目根目录新建 .eslintrc.cjs(或 .js/.json),内容示例如下:
module.exports = {
root: true,
env: { browser: true, es2021: true, node: true },
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
'prettier' // 关闭与 Prettier 冲突的规则
],
parser: '@typescript-eslint/parser',
plugins: ['react', 'react-hooks', '@typescript-eslint'],
rules: {
'no-console': 'warn',
'react/prop-types': 'off',
'react/react-in-jsx-scope': 'off'
}
};
注意:extends 中的 prettier 必须放在最后,才能正确覆盖前面的冲突规则。
配置 Prettier 并对接 ESLint
新建 .prettierrc 文件,定义格式偏好:
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 80
}
再建 .eslintignore 和 .prettierignore,排除 node_modules、dist 等目录。关键一步:在 settings.json(工作区或用户设置)中启用自动修复:
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": ["javascript", "typescript", "typescriptreact", "html"],
"prettier.requireConfig": true,
这样保存文件时,ESLint 就会调用 Prettier 自动格式化 + 修复可修复的问题。
避免常见坑
几个容易出错但很好解决的点:
- 多个项目规则不一致?用 工作区设置(.vscode/settings.json)替代全局设置
- 保存没反应?检查是否启用了
editor.codeActionsOnSave,且文件类型在eslint.validate列表中 - Prettier 报错说“配置未找到”?确认
prettier.requireConfig设为true,且项目根目录有.prettierrc - React 组件报
react/prop-types错误?按需关闭,或装eslint-plugin-prop-types补充校验
基本上就这些。配完你会发现,代码提交前不再需要手动调整缩进、引号、分号——编辑器已经帮你做好了。










