目前在多人项目开发时发现很多代码不规范的地方,因为每个项目都是多人维护,再加上各种历史代码的不同风格,这些情况很容易就造成了代码规范落地难,项目中出现大量低质量代码,代码格式难统一。所以采用 eslint+husky+stylelint+lint-staged+commitlint 这几个工具能够有效解决上述问题。
配置
安装依赖
npm install -D eslint stylelint stylelint-config-standard stylelint-order stylelint-config-css-modules postcss-less husky lint-staged@8 @commitlint/config-conventional @commitlint/cli
1.eslint
定义:ESLint是一个用来识别 ECMAScript 并且按照规则给出报告的代码检测工具,使用它可以避免低级错误和统一代码的风格。如果每次在代码提交之前都进行一次eslint代码检查,就不会因为某个字段未定义为undefined或null这样的错误而导致服务崩溃,可以有效的控制项目代码的质量。
参考官方文档配置好 .eslintrc .eslintignore 文件 https://eslint.bootcss.com/
项目根目录添加.eslintrc 文件,如下:
{
"root": true,
"extends": [
"eslint:recommended"
],
"env": {
"node": true,
"es6": true,
"browser": true
},
"parserOptions": {
"parser": "@babel/eslint-parser",
"ecmaVersion": 2020,
"requireConfigFile": false,
"ecmaFeatures": {
"experimentalDecorators": true,
"experimentalObjectRestSpread": true,
"impliedStrict": true,
"classes": true,
"jsx": true
},
"sourceType": "module"
},
// "plugins": [
// "react"
// ],
"rules": {
//强制统一缩进
"indent": ["error", 4],
// 禁止未使用的变量
"no-unused-vars": 1,
"no-console": [
"error",
{
"allow": [
"log",
"warn",
"error",
"info"
]
}
],
"no-duplicate-case": 2,
// 禁止空语句块
"no-empty": 2,
"no-ex-assign": 2,
"no-extra-boolean-cast": 2,
"no-shadow": 0,
// 禁止 function 定义中出现重名参数
"no-mixed-spaces-and-tabs": [
"error",
"smart-tabs"
],
//使用分号
"semi": [
2,
"always"
],