规范工具:eslint
简介
ESLint 是在 ECMAScript/JavaScript 代码中识别和报告模式匹配的工具,它的目标是保证代码的一致性和避免错误。
一些成熟的eslint规范
[Airbnb JavaScript 代码规范](https://link.juejin.cn/?target=https%3A%2F%2Fgithub.com%2Fairbnb%2Fjavascript "https://github.com/airbnb/javascript")、[Standard JavaScript 规范](https://link.juejin.cn/?target=https%3A%2F%2Fgithub.com%2Fstandard%2Fstandard%2Fblob%2Fmaster%2Fdocs%2FREADME-zhcn.md "https://github.com/standard/standard/blob/master/docs/README-zhcn.md")、[Google JavaScript 规范](https://link.juejin.cn/?target=https%3A%2F%2Fgoogle.github.io%2Fstyleguide%2Fjsguide.html "https://google.github.io/styleguide/jsguide.html")
初始化
npm i eslint -D
npx eslint --init
使用上面命令会生成一个.eslintrc.js配置文件
核心配置
parser-解析器
eslint底层默认是使用expree来进行AST解析,不支持TypeScript,因此需要引入其他解析器完成TS解析
社区提供@typescript-eslint/parser这个解决方案,专门为了 TypeScript 的解析,将 TS 代码转换为 Espree 能够识别的格式
parserOptions - 解析器选项
这个配置可以对上述的解析器进行能力定制,默认情况下 ESLint 支持 ES5 语法,你可以配置这个选项
rules - 具体代码规则
rules 配置即代表在 ESLint 中手动调整哪些代码规则,比如禁止在 if 语句中使用赋值语句这条规则可以像如下的方式配置:
module.exports = {
rules: {
"no-cond-assign": ["error", "alawys"]
}
}
plugins
如上我们说到eslint默认不支持ts的解析,需要@typescript-eslint/parser才能兼容ts解析,此时我们就需要@typescript-eslint/eslint-plugin这个来拓展ts的代码规则
module.exports = {
plugins: ['@typescript-eslint']
}
我们添加了规则集,但是我们没有去启用他,同时我们需要去启用这个规则集
module.exports = {
rules: {
'@typescript-eslint/ban-ts-comment': 'error',
'@typescript-eslint/no-explicit-any': 'warn',
}
}
extends - 继承配置
下面列出三种集成情况:
- 从 ESLint 本身继承;
- 从类似
eslint-config-xxx的 npm 包继承; - 从 ESLint 插件继承。
module.exports = {
"extends": [
// 第1种情况
"eslint:recommended",
// 第2种情况,一般配置的时候可以省略 `eslint-config`
"standard"
// 第3种情况,可以省略包名中的 `eslint-plugin`
// 格式一般为: `plugin:${pluginName}/${configName}`
"plugin:react/recommended"
"plugin:@typescript-eslint/recommended",
]
}
env 和 globals
这两个配置分别表示运行环境和全局变量
Husky + lint-staged 的 Git 提交工作流集成
Husky处理的事情就是再git commit 时,进行代码格式检查,只有确保格式通过校验才能提交代码,下面我们来安装这个工具
npm i husky -D
初始化,并执行husky钩子
npx husky install
npx husky add .husky/pre-commit "npm run lint"
执行上面操作之后每次执行git commit就会执行npm run lint脚本,通过lint之后才能进行提交
但是每次执行npm run lint都会对代码进行全量扫描,所以需要增加配置:
npm i -D lint-staged
然后在 package.json中添加如下的配置:
{
"lint-staged": {
"**/*.{js,jsx,tsx,ts}": [
"npm run lint:script",
"git add ."
],
"**/*.{scss}": [
"npm run lint:style",
"git add ."
]
}
}
将原来的npm run lint替换成npx --no -- lint-staged