ESLint + Prettier 代码规范最佳实践 2026

💡 为什么需要代码规范? 好的代码规范能提升代码可读性、减少 Bug、降低维护成本、统一团队协作风格。ESLint 负责代码质量检查,Prettier 负责代码格式化,两者结合是现代前端项目的标配。
本文将带你从零搭建完整的代码规范体系:
- ✅ ESLint 与 Prettier 核心概念
- ✅ 从零开始配置 ESLint
- ✅ Prettier 格式化配置
- ✅ TypeScript / Vue / React 集成
- ✅ 常用规则集推荐
- ✅ Git 提交自动检查(Husky + lint-staged)
- ✅ CI/CD 集成
- ✅ 常见问题与解决方案
一、基础概念
1.1 ESLint 是什么
ESLint 是一个可组装的 JavaScript 和 JSX 检查工具,用于发现代码中的问题并统一代码风格。
ESLint 的主要能力:
- 🔍 代码检查:发现潜在 Bug 和错误
- 📏 代码规范:统一团队代码风格
- 🔧 自动修复:一键修复大部分问题
- 🧩 高度可配置:按需定制规则
1.2 Prettier 是什么
Prettier 是一个「有态度」的代码格式化工具,支持多种语言,完全接管代码格式。
Prettier 的主要特点:
- ✨ 开箱即用:几乎零配置即可使用
- 🔄 多语言支持:JS/TS/JSX/JSON/CSS/HTML/Markdown 等
- 🤝 彻底统一:消除所有格式争议
- ⚡ 快速高效:秒级格式化整个项目
1.3 为什么两者结合使用
| 工具 | 擅长 | 不擅长 |
|---|---|---|
| ESLint | 代码质量、语法错误、最佳实践 | 格式化(慢且不彻底) |
| Prettier | 代码格式化、风格统一 | 代码质量检查 |
最佳实践: ESLint 管质量,Prettier 管格式,各司其职,完美配合。
二、快速开始
2.1 环境要求
- Node.js: 18+ (推荐 LTS)
- 包管理器: npm / yarn / pnpm
- 编辑器: VS Code(推荐)
2.2 基础项目配置
1. 安装依赖
npm install -D eslint prettier eslint-config-prettier eslint-plugin-prettierpnpm add -D eslint prettier eslint-config-prettier eslint-plugin-prettieryarn add -D eslint prettier eslint-config-prettier eslint-plugin-prettier依赖说明:
eslint- ESLint 核心prettier- Prettier 核心eslint-config-prettier- 关闭 ESLint 中与 Prettier 冲突的格式规则eslint-plugin-prettier- 让 Prettier 规则作为 ESLint 规则运行
2. 创建 ESLint 配置
// .eslintrc.js
module.exports = {
env: {
browser: true,
node: true,
es2022: true
},
extends: [
'eslint:recommended',
'plugin:prettier/recommended'
],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
rules: {}
}3. 创建 Prettier 配置
// .prettierrc.js
module.exports = {
// 每行最大字符数
printWidth: 100,
// 缩进空格数
tabWidth: 2,
// 使用制表符缩进
useTabs: false,
// 语句末尾加分号
semi: false,
// 使用单引号
singleQuote: true,
// 对象属性的引号
quoteProps: 'as-needed',
// JSX 使用单引号
jsxSingleQuote: false,
// 尾随逗号
trailingComma: 'none',
// 对象大括号内空格
bracketSpacing: true,
// 箭头函数参数括号
arrowParens: 'always',
// 行结束符
endOfLine: 'lf'
}4. 创建忽略文件
// .eslintignore
node_modules
dist
build
public
*.min.js// .prettierignore
node_modules
dist
build
public
*.min.js
*.min.css5. 添加 npm scripts
{
"scripts": {
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"format:check": "prettier --check ."
}
}6. 运行检查
# 检查代码问题
npm run lint
# 自动修复
npm run lint:fix
# 格式化代码
npm run format
# 检查格式
npm run format:check三、TypeScript 集成
3.1 安装依赖
npm install -D @typescript-eslint/parser @typescript-eslint/eslint-plugin typescriptpnpm add -D @typescript-eslint/parser @typescript-eslint/eslint-plugin typescript3.2 配置 ESLint
// .eslintrc.js
module.exports = {
env: {
browser: true,
node: true,
es2022: true
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended'
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module'
},
plugins: ['@typescript-eslint'],
rules: {
// 禁止使用 any
'@typescript-eslint/no-explicit-any': 'warn',
// 要求函数返回类型
'@typescript-eslint/explicit-function-return-type': 'off',
// 禁止未使用的变量
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
// 禁止使用 @ts-ignore
'@typescript-eslint/ban-ts-comment': 'warn',
// 类型导入
'@typescript-eslint/consistent-type-imports': 'error'
}
}3.3 TypeScript 配置
// tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true
},
"include": ["src/**/*.ts", "src/**/*.d.ts"],
"exclude": ["node_modules", "dist"]
}四、Vue 3 集成
4.1 安装依赖
npm install -D eslint-plugin-vue vue-eslint-parserpnpm add -D eslint-plugin-vue vue-eslint-parser4.2 配置 ESLint
// .eslintrc.js
module.exports = {
env: {
browser: true,
node: true,
es2022: true
},
extends: [
'eslint:recommended',
'plugin:vue/vue3-recommended',
'plugin:prettier/recommended'
],
parser: 'vue-eslint-parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
parser: '@typescript-eslint/parser'
},
rules: {
// 组件名称多词
'vue/multi-word-component-names': 'off',
// props 默认值
'vue/require-default-prop': 'off',
// v-for 必须有 key
'vue/require-v-for-key': 'error',
// 模板中使用单引号
'vue/html-quotes': ['error', 'double'],
// 自闭合标签
'vue/html-self-closing': [
'error',
{
html: { void: 'always', normal: 'always', component: 'always' }
}
],
// 组件名大小写
'vue/component-name-in-template-casing': ['error', 'PascalCase']
}
}五、React 集成
5.1 安装依赖
npm install -D eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11ypnpm add -D eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y5.2 配置 ESLint
// .eslintrc.js
module.exports = {
env: {
browser: true,
node: true,
es2022: true
},
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
'plugin:jsx-a11y/recommended',
'plugin:prettier/recommended'
],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
ecmaFeatures: {
jsx: true
}
},
settings: {
react: {
version: 'detect'
}
},
rules: {
// React 导入(新 JSX transform 不需要)
'react/react-in-jsx-scope': 'off',
// props 类型(TypeScript 项目可关闭)
'react/prop-types': 'off',
// hooks 依赖
'react-hooks/exhaustive-deps': 'warn',
// 按钮类型
'react/button-has-type': 'error',
// 危险的 dangerouslySetInnerHTML
'react/no-danger': 'warn'
}
}六、常用规则集推荐
6.1 流行规则集对比
| 规则集 | 特点 | 适用场景 |
|---|---|---|
| eslint:recommended | ESLint 官方推荐,基础规则 | 所有项目 |
| standard | JavaScript 标准风格 | 喜欢无分号风格的团队 |
| airbnb | 最严格的规则集,覆盖面广 | 追求高质量的大型团队 |
| Google 风格指南 | 喜欢 Google 风格的团队 | |
| xo | 严格但合理的规则集 | 个人或小团队 |
6.2 推荐配置组合
Vue 3 + TypeScript 项目:
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:vue/vue3-recommended',
'plugin:prettier/recommended'
]React + TypeScript 项目:
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
'plugin:jsx-a11y/recommended',
'plugin:prettier/recommended'
]6.3 必开规则
rules: {
// 禁止未使用的变量
'no-unused-vars': 'warn',
// 禁止未定义的变量
'no-undef': 'error',
// 禁止使用 console(可根据情况调整)
'no-console': ['warn', { allow: ['warn', 'error'] }],
// 禁止使用 debugger
'no-debugger': 'error',
// 禁止重复的 case 标签
'no-duplicate-case': 'error',
// 禁止空的代码块
'no-empty': 'warn',
// 强制使用 ===
'eqeqeq': ['error', 'always'],
// 禁止 var
'no-var': 'error',
// 优先使用 const
'prefer-const': 'error',
// 禁止修改函数参数
'no-param-reassign': 'error'
}七、VS Code 集成
7.1 安装插件
在 VS Code 中安装以下插件:
- ESLint - 代码检查
- Prettier - Code formatter - 代码格式化
7.2 配置 VS Code
// .vscode/settings.json
{
// 默认格式化工具
"editor.defaultFormatter": "esbenp.prettier-vscode",
// 保存时格式化
"editor.formatOnSave": true,
// 保存时自动修复 ESLint 问题
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
// 显示 ESLint 输出通道
"eslint.debug": false,
// 启用 ESLint
"eslint.enable": true,
// Prettier 配置文件路径
"prettier.configPath": ".prettierrc.js",
// 需要 Prettier 的语言
"prettier.documentSelectors": [
"**/*.js",
"**/*.jsx",
"**/*.ts",
"**/*.tsx",
"**/*.vue",
"**/*.json",
"**/*.css",
"**/*.scss",
"**/*.md"
],
// 每行长度参考线
"editor.rulers": [100]
}7.3 推荐的扩展推荐
// .vscode/extensions.json
{
"recommendations": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"editorconfig.editorconfig"
]
}八、Git 提交检查
8.1 使用 Husky + lint-staged
1. 安装依赖
npm install -D husky lint-stagedpnpm add -D husky lint-staged2. 启用 Git Hooks
npx husky install3. 添加 prepare 脚本
{
"scripts": {
"prepare": "husky install"
}
}4. 创建 pre-commit hook
npx husky add .husky/pre-commit "npx lint-staged"5. 配置 lint-staged
// package.json
{
"lint-staged": {
"*.{js,jsx,ts,tsx,vue}": [
"eslint --fix",
"prettier --write"
],
"*.{json,css,scss,md,html}": [
"prettier --write"
]
}
}8.2 提交信息规范
安装 commitlint:
npm install -D @commitlint/cli @commitlint/config-conventional配置 commitlint:
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
[
'feat',
'fix',
'docs',
'style',
'refactor',
'perf',
'test',
'chore',
'revert',
'build',
'ci'
]
],
'subject-case': [0],
'subject-full-stop': [0],
'header-max-length': [2, 'always', 100]
}
}创建 commit-msg hook:
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'九、CI/CD 集成
9.1 GitHub Actions
# .github/workflows/lint.yml
name: Lint
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run ESLint
run: npm run lint
- name: Check Prettier format
run: npm run format:check9.2 GitLab CI
# .gitlab-ci.yml
lint:
stage: test
image: node:20
cache:
paths:
- node_modules/
script:
- npm ci
- npm run lint
- npm run format:check
only:
- merge_requests
- main
- develop十、EditorConfig
EditorConfig 用于统一编辑器基础配置,配合 Prettier 使用效果更佳。
# .editorconfig
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false
[Makefile]
indent_style = tab十一、常见问题
11.1 ESLint 与 Prettier 冲突
现象: ESLint 报的错被 Prettier 格式化后还是报错。
解决方案:
- 确保安装了
eslint-config-prettier - 在
extends中把plugin:prettier/recommended放在最后 - 不要在 ESLint 中配置格式相关的规则
11.2 保存时不自动格式化
检查项:
- 是否安装了 Prettier 插件
editor.formatOnSave是否开启editor.defaultFormatter是否设置正确- 项目根目录是否有 Prettier 配置文件
11.3 部分文件不想检查
在 .eslintignore 或 .prettierignore 中添加:
node_modules
dist
build
*.min.js
public也可以在文件顶部用注释禁用:
/* eslint-disable */
// 这段代码不检查/* eslint-disable no-console */
// 只禁用某个规则
console.log('hello')11.4 旧项目引入 lint 报错太多
解决方案:
- 先用
eslint --fix自动修复能修的 - 把严重错误降为 warning,逐步整改
- 只对新文件严格检查,老文件逐步迁移
- 使用
eslint-nibble逐步修复
# 只检查暂存的文件(推荐)
npx lint-staged十二、配置速查
12.1 完整 Vue 3 + TS 配置
// .eslintrc.js
module.exports = {
root: true,
env: {
browser: true,
node: true,
es2022: true
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:vue/vue3-recommended',
'plugin:prettier/recommended'
],
parser: 'vue-eslint-parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
parser: '@typescript-eslint/parser'
},
rules: {
'vue/multi-word-component-names': 'off',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'no-console': ['warn', { allow: ['warn', 'error'] }],
'prefer-const': 'error',
'eqeqeq': ['error', 'always']
}
}12.2 Prettier 常用配置速查
module.exports = {
printWidth: 100, // 行宽
tabWidth: 2, // 缩进
useTabs: false, // 用空格不用 tab
semi: false, // 无分号
singleQuote: true, // 单引号
trailingComma: 'none', // 无尾随逗号
bracketSpacing: true, // 大括号内空格
arrowParens: 'always', // 箭头函数参数括号
endOfLine: 'lf' // 换行符
}12.3 常用命令速查
# 检查所有文件
eslint .
# 自动修复
eslint . --fix
# 检查指定目录
eslint src/
# 忽略某些文件
eslint . --ignore-pattern "*.test.js"
# 格式化所有文件
prettier --write .
# 检查格式
prettier --check .
# 格式化指定文件
prettier --write src/**/*.js相关文章推荐:
🎯 代码规范不是约束,而是提升团队协作效率和代码质量的利器。越早建立规范,后期维护成本越低。从今天开始,让你的代码更优雅!