本来介绍一下前端常用的代码规范配置工具,本来介绍一下前端常用的代码规范配置工具,作为对这段时间项目的总结。
ESLint
什么是ESLint?它是一个静态代码检查器,用来快速发现问题。
- 发现问题
- 大多数被ESLint发现的问题,也能自动被ESlint修复
- 配置化,预处理代码,使用自定义解析器,编写自己的规则,与ESLint的内置规则一起工作。自定义ESLint,使其完全按照项目所需的方式工作。
安装Eslint,使用如下命令:
npm init @eslint/config
通过与ESlint的脚手架交互设置,可以自动生成如下配置:
例如某个Vue的Eslint配置如下:
module.exports = {
root: true,
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/eslint-config-typescript/recommended',
'@vue/eslint-config-prettier',
'plugin:storybook/recommended',
],
env: {
browser: true,
node: true,
},
parserOptions: {
ecmaVersion: 'latest',
},
overrides: [
{
files: ['cypress/e2e/**.{cy,spec}.{js,ts,jsx,tsx}'],
extends: ['plugin:cypress/recommended'],
},
],
rules: {
'no-console': process.env.NODE_ENV === 'wcm' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'wcm' ? 'error' : 'off',
'space-before-function-paren': 'off',
complexity: ['error', 20],
// 圈复杂度不超过20
'max-depth': ['error', 4],
// 块语句的最大可嵌套深度不要超过4层
'max-nested-callbacks': ['error', 4],
// 回调函数嵌套的层数不超过4层
'no-multi-assign': 'error',
// 禁止连续赋值
'no-undef-init': 'warn',
// 变量不需要用undefined初始化
'consistent-return': ['error'],
// 要求使用一致的 return 语句
'no-alert': 2,
// 禁止使用alert confirm prompt - 禁用
'default-case': 'error',
// 每个switch语句都包含一个default语句,即使它不包含任何代码
'no-fallthrough': 'error',
// 在switch语句的每一个有内容的case中都放置一条break语句
'no-case-declarations': 'error',
// case语句中需要声明词法时, 花括号{}不能省略
'no-empty-function': 'error',
// 禁止出现空函数
'spaced-comment': ['error', 'always'],
// 行注释和块级注释前必须要有空格
'lines-around-comment': [
'error',
{
beforeBlockComment: true,
ignorePattern: 'ignore-beforeBlock-comment',
},
],
'vue/singleline-html-element-content-newline': 'off',
'vue/no-template-shadow': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'vue/no-v-html': 'off',
'vue/html-self-closing': [
'error',
{
html: {
void: 'always',
normal: 'never',
component: 'any',
},
},
],
eqeqeq: ['error', 'always'],
// 使用类型安全的 === 和 !== 操作符代替 == 和 != 操作符
'vue/multi-word-component-names': 'off',
},
}
Prettier
什么是Prettier?它是一个有态度opinionated 的代码格式化工具。
- 代码保存时,代码就被格式化了
- 代码评审时无须争论代码样式
- 节省时间和精力
- 支持多种前端常见语言,js,ts,vue,jsx,tsx,angular,grapql,sass,less
ESlint主要是是代码词法方面的规范配置,而Prettier则是代码样式方面的规范。`
安装方式:
npm i -D prettier
npm i -D eslint-config-prettier eslint-plugin-prettier # 如果想要prettier配合eslint一起使用,就再装这2个插件
例如某个项目prettier的配置:
// 文件名:.prettierrc.js
module.exports = {
// 结尾是否添加分号
semi: false,
// 使用单引号
singleQuote: true,
// 一行代码的最大字符数,默认是80
printWidth: 120,
// <lf|crlf|cr|auto> 行尾换行符,默认是lf,
endOfLine: 'auto',
// (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号
arrowParens: 'avoid',
// 一个tab占2个空格
tabWidth:'2'
}
在Eslint中配置prettier:
// 文件名 eslint.js
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'plugin:vue/vue3-essential',
'standard-with-typescript',
+ 'plugin:prettier/recommended',
],
overrides: [],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
+ plugins: ['vue', 'prettier'],
rules: {},
}
EditorConfig
EditorConfig有助于为跨不同编辑器和IDE在同一项目中工作的多个开发人员维护一致的编码样式。
PS:如果使用的是VsCode作为代码编辑器,需要装EditorConfig插件。如果使用WebStorm,则无须下载插件,因为webStorm内置EditorConfig。
例如某个项目的EditorConfig的配置:
// 文件名 .editorconfig
root = true
[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
end_of_line = lf # 控制换行类型(lf | cr | crlf)
insert_final_newline = true # 始终在文件末尾插入一个新行
indent_style = tab # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
max_line_length = 120 # 最大行长度
[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off # 关闭最大行长度限制
trim_trailing_whitespace = false # 关闭末尾空格修剪
Husky
如果想要代码提交前自动使用Prettier格式化代码,Eslint检查代码错误,则可以使用Husky插件。Husky支持所有的Git钩子,这样在提交前/后,可以对项目进行一些操作。
在项目中,可以使用lint-staged,commitlint配合husky一起使用:
-
lint-staged: 如果全量对代码进行lint检查,会导致检查用时过长,特别是当项目越来越大后。因此使用lint-staged可以只对git 暂存区的代码进行lint校验。npm install --save-dev lint-staged -
commitlint: 使用这个插件对commit的消息进行规范校验npm install -g @commitlint/cli @commitlint/config-conventional
husky配置:
提交前:对代码进行ts类型检查,lint检查和格式化
# 文件目录 .husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
echo "type-checking 🧐"
npm run type-check || (
echo "Failed to run type-check, please make the changes required above🥴"
false;
)
echo "running format and lint"
npx lint-staged || (
echo "Failed to run format or lint, please make the changes required above"
false;
)
对代码commit信息进行校验:
# 文件目录 .husky/commit-msg
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no -- commitlint --edit
合并代码后,自动下载npm包
# 文件目录 .husky/post-merge
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npm i
配置lint-staged
// 文件名package.json
{
"lint-staged": {
"**/*.{js,ts,jsx,tsx,vue}": [
"npm run format",
"npm run lint"
]
}
}