前言
我曾在大大小小的各种公司工作过,但无论大小都没有看到前端有明确的统一的编码规范。也可能是稍大点公司的编码水平都还不错,所以代码风格大差不差,以至于没人重视吧。
后来我回到苏州,发现苏州的编码水平参差不齐的。大部分项目编码用的都是4空格缩进,常量到处用var、let,各种非驼峰命名,单行对象大括号没有空格间隔,多行对象结尾没有逗号,行尾各种多余的空格等等各种非主流的ugly代码。每当我要维护这种项目时,都被迫遵循他们老的编码规范,不然就会产生巨多diff,很不利于代码review,在开发过程中总有种既熟悉又陌生的感觉。
痛定思痛,我觉得很有必要在公司推行统一编码规范。以下是我结合自己经验和 chatgpt 总结出来的一套编码规范,如有错漏还望斧正。
eslint+prettier+editorconfig 实现编码规范统一
EditorConfig可以保证跨编辑器风格统一,Prettier配置保证代码格式化规则一致,ESLint使用后可以避免部分低级代码语法和逻辑错误(no-var, prefer-const, no-unused-vars),同时使用了plugin:vue/recommended等插件继承官方推荐规则。
统一编码规范能最大程度避免因个人编码风格不同导致的文件格式化改动产生太多diff和历史修改记录混乱,同时降低改动他人代码时的心智负担。
以下是根据社区广泛使用的编码规范整理而成。老项目可以将部分设置降级,但新项目一定要严格执行新规范。
(建议老项目的代码提交时的自动修复操作(commitlint)暂时不做,因为老项目自动修复会导致过量的 diff ,不利于团队推广。)
.prettierrc 文件
配置代码的格式化规则,用于统一代码的排版风格
需要安装vscode插件 prettier
官方文档:prettier.node.org.cn/docs/en/opt...
json
{
"printWidth": 120,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true,
"jsxSingleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "avoid",
"vueIndentScriptAndStyle": false,
"endOfLine": "lf",
"singleAttributePerLine": false,
"proseWrap": "never",
"htmlWhitespaceSensitivity": "ignore"
}
.eslintrc.js 文件(vue2版本)
用于检查和规范 JavaScript/TypeScript/Vue 等源代码的质量与风格。
需要安装vscode插件 eslint
官方文档:zh-hans.eslint.org/docs/latest...
- 安装
bash
npm install -D eslint@7.32.0 eslint-plugin-vue@8.0.3 vue-eslint-parser@10.1.4 prettier@2.8.8 eslint-config-prettier@8.3.0 eslint-plugin-prettier@4.0.0 @babel/eslint-parser@7.27.5 --legacy-peer-deps
- 配置
js
module.exports = {
root: true,
env: {
node: true,
browser: true,
es2021: true,
},
extends: ['plugin:vue/recommended', 'eslint:recommended', 'plugin:prettier/recommended'],
plugins: ['prettier', 'vue'],
parser: 'vue-eslint-parser',
parserOptions: {
parser: '@babel/eslint-parser',
ecmaVersion: 2020,
sourceType: 'module',
},
rules: {
// 通用规则
'prettier/prettier': ['error', { endOfLine: 'auto' }],
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-unused-vars': ['off', { vars: 'all', args: 'after-used', ignoreRestSiblings: false }],
'no-var': 'error',
camelcase: ['error', { properties: 'always' }],
'arrow-body-style': ['off', 'as-needed'],
'comma-dangle': [
'error',
{
arrays: 'always-multiline',
objects: 'always-multiline',
imports: 'always-multiline',
exports: 'always-multiline',
functions: 'never',
},
],
'prefer-const': [
'error',
{
destructuring: 'all', // 解构出来的变量也检查
ignoreReadBeforeAssign: true,
},
],
'key-spacing': ['error', { beforeColon: false, afterColon: true }],
// Vue 相关规则
'vue/component-name-in-template-casing': ['error', 'PascalCase'],
'vue/order-in-components': 'error',
'vue/attributes-order': 'error',
// 放宽规则(慎用)
'vue/multi-word-component-names': 'off',
'vue/singleline-html-element-content-newline': 'off',
'vue/no-v-html': 'off',
},
}
.editorconfig 文件
统一不同编辑器和 IDE 的代码风格(缩进、换行符、字符集等),确保团队代码基础格式一致。
bash
# EditorConfig 统一不同编辑器代码风格
# 表示这是项目根目录下的顶级 .editorconfig 文件,编辑器在查找配置时会停止向上查找
root = true
# 匹配所有文件
[*]
# 使用空格缩进
indent_style = space
# 缩进大小为 2
indent_size = 2
# 使用 UTF-8 编码
charset = utf-8
# 注掉end_of_line,避免因为 IDE 保存时"自动格式化"导致每行都变
# end_of_line = lf
# 文件末尾会插入一个空行
insert_final_newline = true
# 是否去除行末多余的空格
trim_trailing_whitespace = true
# 最大行宽
max_line_length = 120
# 匹配 JavaScript 等文件
[*.js, *.ts, *.vue]
# 匹配 Markdown 文件
[*.md]
# 使用制表符缩进
indent_style = tab
.gitattributes 文件
统一仓库换行符存储格式
老项目配置完.gitattributes文件后需要清下缓存才能生效:(如果清缓存了,那么 .editorconfig文件的 end_of_line = lf 配置就可以放开了)
bash
git rm --cached -r .
git reset --hard
bash
# ==============================
# 基础设置
# ==============================
# 默认所有文本文件自动处理换行符
* text=auto
# ==============================
# 强制 LF 的文本文件
# ==============================
# 源代码
*.js text eol=lf
*.jsx text eol=lf
*.ts text eol=lf
*.tsx text eol=lf
*.vue text eol=lf
# 样式
*.css text eol=lf
*.scss text eol=lf
*.sass text eol=lf
*.less text eol=lf
# 配置/标记文件
*.json text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.html text eol=lf
*.xml text eol=lf
*.md text eol=lf
*.txt text eol=lf
*.npmrc text eol=lf
*.prettierrc text eol=lf
*.editorconfig text eol=lf
*.gitignore text eol=lf
*.gitattributes text eol=lf
# Shell / 脚本文件
*.sh text eol=lf
*.bash text eol=lf
*.zsh text eol=lf
# ==============================
# 二进制文件(禁止 Git 改行)
# ==============================
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.svg binary
*.webp binary
*.zip binary
*.gz binary
*.tar binary
*.7z binary
*.pdf binary
*.ttf binary
*.woff binary
*.woff2 binary
换行符 Git 配置
(配置.gitattributes 文件后该设置就无效了)
1. core.autocrlf
控制 Git 在提交/检出时是否自动转换换行符
true
-
- 检出到工作区:把 LF 转成 CRLF(适合 Windows 本地编辑器)
- 提交到仓库 :把 CRLF 转回 LF
👉 保证仓库里统一是 LF,本地是 CRLF
input
-
- 检出时不改(保持 LF)
- 提交时 CRLF 转 LF
👉 常用于 Mac/Linux,避免仓库进 CRLF
false
-
- 提交/检出都不做换行符转换
👉 保持文件原样,CRLF 就 CRLF,LF 就 LF
- 提交/检出都不做换行符转换
2. core.safecrlf
控制 当 Git 检测到换行符不一致时,是否阻止提交
true
-
- 提交时如果有 混合换行符(LF + CRLF) 或 CRLF 会被替换成 LF → 阻止提交
👉 起到"安全阀"的作用
- 提交时如果有 混合换行符(LF + CRLF) 或 CRLF 会被替换成 LF → 阻止提交
false
-
- Git 不做安全检查
👉 即使有换行符转换风险(比如 CRLF → LF),也允许提交
- Git 不做安全检查
建议设置(避免其他同事遇到提交代码失败的场景):
bash
git config --global core.autocrlf false
git config --global core.safecrlf false
.eslintignore 文件
package.json 等文件默认会被 eslint 的检查,从而飘红。设置忽略文件避免 eslint 检查。
bash
# 依赖
node_modules/
# 构建产物
dist/
build/
coverage/
public/
# 配置文件
*.config.js
*.d.ts
package.json
package-lock.json
yarn.lock
pnpm-lock.yaml
.env
.env.*
# 日志 & 系统文件
*.log
.DS_Store
# 忽略所有非 src 下的源码(推荐做法)
/*
!/src
总结
在实际老项目应用期间,发现由于设置了 .editorconfig 文件的end_of_line = lf
,导致保存时候整个文件全部变动了,都没法看 diff 了哪行代码。
总之在使用过程中可能会碰见各种问题,多亏有了 chatgpt (真的甩 deepseek 几条街)老师,现在你已经是个编码大神了。