前端代码规范简易版本

前端代码规范简易版本

eslint 规范

1
pnpm add eslint eslint-plugin-vue @typescript-eslint/parser @typescript-eslint/eslint-plugin -D
  • eslint:eslint 核心代码,用于代码校验
  • eslint-plugin-vue:eslint 插件,用于 vue 文件的校验
  • @typescript-eslint/parser:eslint 插件,用于解析 typescript 文件
  • @typescript-eslint/eslint-plugin:eslint 插件,用于 typescript 文件的校验

prettier 规范

1
pnpm add prettier eslint-config-prettier eslint-plugin-prettier -D
  • prettier:prettier 核心代码,用于代码格式化
  • eslint-config-prettier:解决ESLint中的样式规范和prettier中样式规范的冲突,以prettier的样式规范为准,使ESLint中的样式规范自动失效
  • eslint-plugin-prettier:将prettier作为ESLint规范来使用

配置

.prettierc.js

1
2
3
4
5
6
7
8
9
10
11
12
module.exports = {
printWidth: 120, // 换行字符串阈值
tabWidth: 2, // tab字符串阈值
useTabs: false, // 是否使用tab缩进
semi: false, // 句末是否加分号
singleQuote: true, // 单引号
trailingComma: 'none', // 是否使用尾逗号
bracketSpacing: true, // 对象数组加空格
jsxBracketSameLine: false, // 是否在jsx中的>换行
arrowParens: 'always', // 箭头函数参数是否加括号
"prettier.ignorePath": ".prettierignore" // 忽略文件
}

.prettierignore

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
.DS_Store
node_modules/
unpackage/
dist/

# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.project
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*

番外

  • prettier/@typescript-eslint:使得@typescript-eslint中的样式规范失效,遵循prettier中的样式规范
  • plugin:prettier/recommended:使用prettier中的样式规范,且如果使得ESLint会检测prettier的格式问题,同样将格式问题以error的形式抛出

使用 husky 和 lint-staged 在代码提交时进行检测

1
pnpm add husky lint-staged -D

执行命令:husky install

执行命令:npx husky add .husky/pre-commit "npx lint-staged"

package.json 中添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"lint-staged": {
"*.js": [
"prettier --write",
"eslint --fix"
],
"*.vue": [
"prettier --parser=vue --write",
"eslint --fix"
],
"*.ts": [
"prettier --write",
"eslint --fix"
],
"*.tsx": [
"prettier --write",
"eslint --fix"
],
"*.css": [
"prettier --write"
],
"*.md": [
"prettier --write --parser markdown --prose-wrap never",
"eslint --fix"
]
}

Something wrong with this article? Click here to submit your revision.

Vector Landscape Vectors by Vecteezy

作者

CrazyChenzi

发布于

2021-12-09

许可协议

CC BY-NC-SA 4.0

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×