下面是一张企业级代码管理和CI/CD的流程图。
那我们今天要了解的就是本地插件检测以及precommit check.
Linters vs Prettier
linters分为两类:
- 格式规则:单行代码长度、tab长度、空格、逗号表达式等
- 代码质量规则:未使用变量、三等号、全局变量声明等
Eslint包含代码格式和代码质量两类,但是主要是代码质量检测
Prettier则只包含代码格式检测,并格式化代码
Eslint github上有这样一段描述:
Does Prettier replace ESLint?
No, ESLint does both traditional linting (looking for problematic patterns) and style checking (enforcement of conventions). You can use ESLint for everything, or you can combine both using Prettier to format your code and ESLint to catch possible errors.
看起来描述是ESlint可以做代码格式和代码质量检查,可以单独使用ESLint来完成这两件事。也可以用perttier做代码格式检查,eslint做代码质量检查。
那我们下面就结合ESLint和Prettier来实现静态代码规范和检查。
ESLint
ESlint概述
ESLint 是在 ECMAScript/JavaScript 代码中识别和报告模式匹配的工具,它的目标是保证代码的一致性和避免错误。在许多方面,它和 JSLint、JSHint 相似,除了少数的例外:
- ESLint 使用 Espree 解析 JavaScript。
- ESLint 使用 AST 去分析代码中的模式
- ESLint 是完全插件化的。每一个规则都是一个插件并且你可以在运行时添加更多的规则。
ESlint集成
你可以使用 yarn 安装 ESLint:
$ yarn add eslint --save-dev
如果是全局安装可以运行下面命令生成.eslintrc.js文件
$ eslint --init
配置形式:
module.exports = {
parser: {}, //定义ESLint的解析器
extends: [], // 定义文件继承的子规范
plugins: [], // 定义了该eslint文件所依赖的插件
env: {},
rules: {} // 规则
};
ESLint配置
module.exports = {
parser: 'esprima', //定义ESLint的解析器,默认为esprima
extends: ['"eslint:recommended"'],//定义文件继承的子规范
plugins: ['@typescript-eslint'],//定义了该 eslint 文件所依赖的插件
env:{
browser: true,
node: true, },
globals: {
Vue: 'readonly',
d3: 'readonly',
},
parserOptions: {
parser: '@typescript-eslint/parser', // 解析 .ts 文件
ecmaVersion: 2019,
sourceType: 'module',
ecmaFeatures: {
modules: true,
},
},
rules: {
"no-console": "off",
......
}
}
ESlint检测
node script
"scripts": {
"lint": "eslint --fix"
}
Prettier
What is Prettier?
Prettier is an opinionated code formatter
翻译过来:Prettier就是一个固执己见的代码格式化程序。
Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.
Why Prettier?
- “We want to free mental threads and end discussions around style. While sometimes fruitful, these discussions are for the most part wasteful.”
- “Literally had an engineer go through a huge effort of cleaning up all of our code because we were debating ternary style for the longest time and were inconsistent about it. It was dumb, but it was a weird on-going “great debate” that wasted lots of little back and forth bits. It’s far easier for us all to agree now: just run Prettier, and go with that style.”
- “Getting tired telling people how to style their product code.”
- “Our top reason was to stop wasting our time debating style nits.”
- “Having a githook set up has reduced the amount of style issues in PRs that result in broken builds due to ESLint rules or things I have to nit-pick or clean up later.”
- “I don’t want anybody to nitpick any other person ever again.”
- “It reminds me of how Steve Jobs used to wear the same clothes every day because he has a million decisions to make and he didn’t want to be bothered to make trivial ones like picking out clothes. I think Prettier is like that.”
How to Use?
有关Prettier的包都可以在这里查看:
// 放在项目根目录的 .prettierrc.js 文件
module.exports = {
printWidth: 100, // 单行最大长度
tabWidth: 2, // 设置编辑器每一个水平缩进的空格数
semi: false, // 在句尾添加分号
singleQuote: true, // 使用单引号
trailingCommas: 'es5', // 在任何可能的多行中输入尾逗号。
bracketSpacing: true, // 在对象字面量声明所使用的的花括号后({)和前(})输出空格
jsxBracketSameLinte: false, // 在多行JSX元素最后一行的末尾添加 > 而使 > 单独一行(不适用于自闭和元素)
alwaysParens: 'always' // 为单行箭头函数的参数添加圆括号。
}
当ESlint和Prettier冲突了怎么解决?
首先安装
yarn add prettier eslint-config-prettier eslint-plugin-prettier -D
对每个依赖进行说明:
-
`prettier`:`Prettier`插件的核心代码。
-
`eslint-config-prettier`:解决`ESLint`中的样式规范和`Prettier`中样式规范的冲突,以 `Prettier` 的样式规范为准,使 `ESLint` 中的样式规范自动失效。
-
`eslint-plugin-prettier`:将 `prettier` 作为 `ESLint` 规范来使用。
1. 修改.eslintrc.js文件,引入Prettier
extends:[
"eslint:recommended",
"plugin:prettier/recommended",
],
rules: {
'prettier/prettier': 'error'
}
2. 修改vscode settings.json
"[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" },
"editor.formatOnSave":true
3. 再保存一个老的js文件,出现了一些报错信息,鼠标移上去就显示
“Delete” ‘CR’
这里从git pull下来的格式是CR/LF。但是本地是CRLF(window)的,于是就报了这个错
解决办法就是在.prettierrc.js加一行配置
endOfLine: "crlf",
4. 这里需要注意把换行改成CRLF之后,提交上去的代码要求LF格式的时候,这个时候全局设置下git
git config --global core.autocrlf true
Git可以在你push时自动地把行结束符CRLF转换成LF,而在pull代码时把LF转换成CRLF。用core.autocrlf来打开此项功能,如果是在Windows系统上,把它设置成true,这样当签出代码时,LF会被转换成CRLF