本文介绍如何搭建前端代码规范体系,包括代码格式化、代码检查、Git 提交规范等内容,适用于任何前端项目。
目录
- 1. 为什么需要代码规范
- 2. 规范工具介绍
- 3. Prettier 配置
- 4. ESLint 配置
- 5. VSCode/Cursor 编辑器配置
- 6. Husky 和 Git 钩子
- 7. Pre-commit 钩子详解
- 8. 命名规范
- 9. 实战步骤
- 10. 常见问题
1. 为什么需要代码规范
代码规范带来的好处
| 好处 | 说明 |
|---|---|
| 代码风格统一 | 团队成员编写的代码风格一致,易于阅读 |
| 提高代码质量 | 自动检查潜在问题,减少 bug |
| 自动化检查 | 提交前自动检查,防止低质量代码进入仓库 |
| 节省 Review 时间 | 减少「代码格式不正确」这类反馈 |
| 新人友好 | 新成员快速适应项目代码风格 |
常见的代码问题
- 缩进不一致(空格 vs Tab)
- 单引号 vs 双引号混用
- 是否使用分号不统一
- 未使用的变量
- 潜在的空值引用
- …
这些问题都可以通过自动化工具解决!
2. 规范工具介绍
Prettier - 代码格式化
Prettier 是一个固执的代码格式化工具。
特点:
- 只关心格式,不关心代码质量
- 配置简单,开箱即用
- 支持几乎所有前端语言
作用:
- 自动统一缩进、引号、分号等格式
- 让团队成员不再争论代码风格
ESLint - 代码质量检查
ESLint 是可配置的 JavaScript 代码检查工具。
特点:
- 可配置规则集
- 插件生态丰富
- 可自动修复部分问题
作用:
- 发现代码中的潜在问题
- 强制执行最佳实践
- 提高代码可维护性
Husky - Git 钩子管理
Husky 让 Git 钩子管理变得简单。
作用:
- 在 Git 操作时自动执行脚本
- 如提交前检查代码、运行测试
lint-staged - 只检查暂存文件
lint-staged 只对 Git 暂存区的文件运行检查。
作用:
- 只检查本次修改的文件,速度更快
- 自动修复可修复的问题
3. Prettier 配置
安装
npm install -D prettier
配置文件
在项目根目录创建 .prettierrc:
{
"semi": false, // 不使用分号
"singleQuote": true, // 使用单引号
"printWidth": 100, // 每行最大字符数
"tabWidth": 2, // 缩进空格数
"useTabs": false, // 使用空格缩进
"trailingComma": "es5", // ES5 允许的尾随逗号
"bracketSpacing": true, // 对象括号内添加空格
"arrowParens": "avoid", // 箭头函数单参数时省略括号
"endOfLine": "lf" // 使用 LF 换行符
}
常用配置项说明
| 配置项 | 值 | 说明 |
|---|---|---|
semi |
false |
不使用分号 |
singleQuote |
true |
使用单引号 |
printWidth |
100 |
每行最大 100 字符 |
tabWidth |
2 |
缩进 2 个空格 |
useTabs |
false |
使用空格而非 Tab |
trailingComma |
"es5" |
在 ES5 允许的地方使用尾随逗号 |
arrowParens |
"avoid" |
箭头函数单参数时省略括号 |
endOfLine |
"lf" |
使用 LF 换行符(跨平台一致) |
忽略文件
创建 .prettierignore:
node_modules
dist
build
coverage
*.min.js
*.min.css
package-lock.json
yarn.lock
pnpm-lock.yaml
使用方法
# 格式化所有文件
npx prettier --write .
# 格式化指定文件
npx prettier --write "src/**/*.js"
# 检查格式(不修改)
npx prettier --check .
添加到 package.json
{
"scripts": {
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,vue,json,scss,css,md}\""
}
}
使用:npm run format
4. ESLint 配置
安装
# 基础安装
npm install -D eslint
# Vue 项目
npm install -D eslint-plugin-vue babel-eslint
# React 项目
npm install -D eslint-plugin-react @typescript-eslint/parser
# 集成 Prettier
npm install -D eslint-plugin-prettier eslint-config-prettier
配置文件
在项目根目录创建 .eslintrc.js:
module.exports = {
root: true,
env: {
node: true, // Node.js 环境
browser: true, // 浏览器环境
es6: true, // ES6 语法
},
extends: [
'eslint:recommended', // ESLint 推荐规则
'plugin:prettier/recommended', // Prettier 集成
],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'warn', // Prettier 冲突时警告
'no-console': 'off', // 允许 console
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
},
parserOptions: {
ecmaVersion: 2020, // ECMAScript 版本
sourceType: 'module', // 使用 ES Modules
},
};
Vue 项目配置示例
module.exports = {
root: true,
env: {
node: true,
browser: true,
},
extends: [
'plugin:vue/essential', // Vue 规则
'plugin:prettier/recommended', // Prettier 集成
'prettier/vue', // Vue Prettier
],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'warn',
'vue/multi-word-component-names': 'off', // 允许单词组件名
'vue/no-v-html': 'off', // 允许 v-html
},
parserOptions: {
parser: 'babel-eslint',
},
};
常用规则说明
| 规则 | 说明 |
|---|---|
no-console |
禁用 console(开发环境可关闭) |
no-debugger |
禁用 debugger(生产环境开启) |
no-unused-vars |
禁止未使用的变量 |
no-undef |
禁止使用未声明的变量 |
eqeqeq |
强制使用 === 和 !== |
使用方法
# 检查代码
npx eslint .
# 自动修复
npx eslint --fix .
# 指定文件类型
npx eslint --ext .js,.vue .
添加到 package.json
{
"scripts": {
"lint": "eslint --ext .js,.jsx,.ts,.tsx,.vue src",
"lint:fix": "eslint --ext .js,.jsx,.ts,.tsx,.vue src --fix"
}
}
5. VSCode/Cursor 编辑器配置
创建配置文件
在项目根目录创建 .vscode/settings.json:
{
// 编辑器设置
"editor.formatOnSave": true, // 保存时自动格式化
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true // 保存时自动修复 ESLint
},
"editor.defaultFormatter": "esbenp.prettier-vscode", // 默认格式化工具
"editor.tabSize": 2, // 缩进大小
"editor.insertSpaces": true, // 使用空格缩进
// 文件配置
"files.eol": "\n", // 换行符为 LF
"files.trimTrailingWhitespace": true, // 保存时删除尾部空格
"files.insertFinalNewline": true, // 保存时在文件末尾插入新行
// ESLint 配置
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"vue"
],
// Vue 配置(如果有)
"vetur.format.defaultFormatter.html": "prettier",
"vetur.format.defaultFormatter.js": "prettier",
"vetur.format.defaultFormatter.css": "prettier",
"vetur.format.defaultFormatter.scss": "prettier"
}
推荐扩展
创建 .vscode/extensions.json:
{
"recommendations": [
"esbenp.prettier-vscode", // Prettier
"dbaeumer.vscode-eslint", // ESLint
"octref.vetur", // Vue 支持(Vue 项目)
"bradlc.vscode-tailwindcss" // Tailwind CSS(如需要)
]
}
工作原理
当你在编辑器中按 Ctrl + S(或 Cmd + S)保存时:
- Prettier 格式化 - 自动调整代码格式
- ESLint 自动修复 - 自动修复可修复的问题
- 提交代码 - 代码已经是规范的了!
6. Husky 和 Git 钩子
Husky 是什么?
Husky 是一个 Git 钩子管理工具,让你可以轻松地在 Git 操作时执行脚本。
安装
npm install -D husky
# Husky v4
npx husky install
# Husky v6+
npm pkg set scripts.prepare="husky install"
npx husky install
配置方式
方式一:package.json(适用于 Husky v4)
{
"husky": {
"hooks": {
"pre-commit": "npm run lint",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
}
方式二:.husky 目录(适用于 Husky v6+)
# 添加 pre-commit 钩子
npx husky add .husky/pre-commit "npm run lint"
# 添加 commit-msg 钩子
npx husky add .husky/commit-msg "commitlint --edit $1"
配合 lint-staged
npm install -D lint-staged
在 package.json 中配置:
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,jsx,ts,tsx,vue}": [
"eslint --fix",
"prettier --write"
],
"*.{json,scss,css,md}": [
"prettier --write"
]
}
}
7. Pre-commit 钩子详解
什么是 Git 钩子?
Git 钩子是 Git 在特定事件发生时自动执行的脚本。你可以用它来自动化开发工作流。
常见的 Git 钩子
| 钩子 | 触发时机 | 典型用途 |
|---|---|---|
| pre-commit | 执行 git commit 后,提交前 |
代码检查、格式化 |
| commit-msg | 提交信息编辑完成后 | 检查提交信息格式 |
| pre-push | 执行 git push 后,推送前 |
运行测试 |
| post-commit | 提交完成后 | 发送通知 |
| post-merge | 合并完成后 | 清理临时文件 |
Pre-commit 钩子的作用
在项目中,pre-commit 钩子主要用于:
- 代码质量检查 - ESLint 检查代码质量
- 代码格式化 - Prettier 统一代码格式
- 运行测试 - 确保提交前测试通过
- 防止低质量代码 - 有问题时阻止提交
工作流程
git add .
git commit
# ↓ pre-commit 钩子触发
lint-staged 获取暂存文件
↓
对 .js/.vue 文件运行 eslint --fix
↓
对所有文件运行 prettier --write
↓
是否有错误?
├─ 是 → 提交被阻止,显示错误信息
└─ 否 → 继续提交
为什么需要 Pre-commit?
| 没有 Pre-commit | 有 Pre-commit |
|---|---|
| 提交后才发现格式问题 | 提交前自动修复 |
| Review 时指出格式问题 | Review 关注业务逻辑 |
| 低质量代码进入仓库 | 阻止低质量代码 |
| 手动运行检查命令 | 自动化检查 |
8. 命名规范
文件命名
# 组件文件(kebab-case,短横线命名)
user-card.vue
article-list.js
# 工具文件(kebab-case)
utils.js
date-format.js
# 样式文件(kebab-case)
main.scss
button.css
# 测试文件(kebab-case + .test 或 .spec)
user-card.test.js
button.spec.js
组件命名
// 组件注册名(PascalCase,大驼峰)
export default {
name: 'UserCard',
// ...
}
// 模板中使用(kebab-case,短横线)
<template>
<user-card />
</template>
变量命名
// 普通变量(camelCase,小驼峰)
const userName = 'John'
const articleList = []
// 常量(UPPER_SNAKE_CASE,大写下划线)
const MAX_COUNT = 100
const API_BASE_URL = 'https://api.example.com'
const DEFAULT_PAGE_SIZE = 20
// 布尔值(is/has/should 前缀)
const isLoading = true
const hasPermission = false
const shouldUpdate = true
const isLoggedIn = true
// 私有变量(下划线前缀)
const _privateVar = 'secret'
函数命名
// 普通函数(camelCase)
function getUserInfo() {}
function formatDate() {}
// 事件处理函数(handle + 动作名)
function handleClick() {}
function handleSubmit() {}
function handleInputChange() {}
// 生命周期(on + 事件名)
function onMounted() {}
function onDestroyed() {}
// 异步函数(async + 动作名)
async function fetchUserData() {}
async function saveArticle() {}
类命名
// PascalCase(大驼峰)
class UserService {}
class ArticleManager {}
class EventBus {}
9. 实战步骤
步骤一:安装依赖
# 安装 Prettier
npm install -D prettier
# 安装 ESLint(Vue 项目)
npm install -D eslint eslint-plugin-vue babel-eslint
# 安装 Prettier 集成
npm install -D eslint-plugin-prettier eslint-config-prettier
# 安装 Husky 和 lint-staged
npm install -D husky lint-staged
步骤二:创建配置文件
Prettier 配置 - 创建 .prettierrc:
{
"semi": false,
"singleQuote": true,
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"trailingComma": "es5",
"endOfLine": "lf"
}
ESLint 配置 - 创建 .eslintrc.js:
module.exports = {
root: true,
env: {
node: true,
browser: true,
},
extends: [
'eslint:recommended',
'plugin:prettier/recommended',
],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'warn',
},
};
步骤三:配置 package.json
{
"scripts": {
"lint": "eslint --ext .js,.vue src",
"lint:fix": "eslint --ext .js,.vue src --fix",
"format": "prettier --write \"**/*.{js,vue,json,scss,md}\""
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,vue}": [
"eslint --fix",
"prettier --write"
],
"*.{json,scss,md}": [
"prettier --write"
]
}
}
步骤四:创建编辑器配置
创建 .vscode/settings.json:
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
步骤五:初始化 Husky
# Husky v4
npx husky install
# Husky v6+
npm pkg set scripts.prepare="husky install"
npm run prepare
步骤六:测试
# 运行格式化
npm run format
# 运行检查
npm run lint
# 提交代码测试
git add .
git commit -m "test: 添加代码规范"
10. 常见问题
Q1: 保存时没有自动格式化?
A:
- 确认是否安装了 Prettier 扩展
- 检查
.vscode/settings.json配置 - 重启编辑器
- 确认文件的默认格式化工具是否为 Prettier
Q2: Git 提交被阻止怎么办?
A:
- 查看错误信息
- 运行
npm run lint:fix自动修复 - 手动修复无法自动修复的问题
- 重新提交
Q3: 如何格式化单个文件?
A:
# 命令行
npx prettier --write "src/index.js"
# 编辑器中保存文件
Q4: 如何禁用某行的 ESLint 检查?
A:
// 禁用下一行
// eslint-disable-next-line
const unusedVar = 'test'
// 禁用当前行
const unusedVar = 'test' // eslint-disable-line
// 禁用整块
/* eslint-disable */
const unusedVar = 'test'
/* eslint-enable */
Q5: Prettier 和 ESLint 冲突怎么办?
A:
使用 eslint-plugin-prettier 和 eslint-config-prettier,让 Prettier 的配置优先:
{
"extends": [
"eslint:recommended",
"plugin:prettier/recommended" // 放在最后
]
}
Q6: Husky 钩子不生效?
A:
# 重新初始化 Husky
rm -rf .git/hooks
npm install
# Husky v4
npx husky install
# Husky v6+
npm run prepare
Q7: lint-staged 没有运行?
A:
- 确认文件已暂存(
git add) - 检查
.gitignore是否忽略了这些文件 - 查看控制台是否有错误
Q8: 如何检查配置是否生效?
A:
# 检查 Prettier 配置
npx prettier --find-config-path
# 检查 ESLint 配置
npx eslint --print-config .js
# 测试格式化
echo "const a=1" | npx prettier --stdin
总结
建立前端代码规范体系带来的价值:
✅ 代码风格统一 - 团队协作更顺畅
✅ 提高代码质量 - 减少潜在 bug
✅ 自动化检查 - 节省人工检查时间
✅ 防止低质量代码 - 提交前自动拦截
✅ 新人友好 - 快速融入团队
关键要点
- Prettier - 负责代码格式化
- ESLint - 负责代码质量检查
- 编辑器配置 - 保存时自动格式化
- Husky + lint-staged - 提交前自动检查
推荐阅读
希望这篇文章对你有帮助!有任何问题欢迎交流。