使用eslint统一代码风格&&提交前检查&&VScode配置自动修复
1. 项目中集成eslint
全局安装eslint,同时作为项目依赖安装。
cnpm i eslint -g cnpm i eslint -D
生成eslint配置文件
eslint --init

生成 .eslintrc.js (选择react Airbnb扩展)
module.exports = {
env: {
browser: true, // 浏览器环境中的全局变量。
es6: true, // 启用除了 modules 以外的所有 ECMAScript 6 特性(该选项会自动设置 ecmaVersion 解析器选项为 6)。
node: true, // Node.js 全局变量和 Node.js 作用域。
},
// extends 属性值可以省略包名的前缀 eslint-config-airbnb。
extends: [
'plugin:react/recommended',
'airbnb',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
// 解析器选项
parserOptions: {
ecmaFeatures: {
jsx: true, // 启用 JSX 支持 JSX 语法并不等同于支持 React,同时启用 plugins设置
},
ecmaVersion: 2018, // 默认设置为 3,5(默认), 你可以使用 6、7、8、9 或 10 来指定你想要使用的 ECMAScript 版本。你也可以用使用年份命名的版本号指定为 2015(同 6),2016(同 7),或 2017(同 8)或 2018(同 9)或 2019 (same as 10)
sourceType: 'module', // 设置为 "script" (默认) 或 "module"(如果你的代码是 ECMAScript 模块)。
},
// 使用第三方插件 插件名称可以省略 eslint-plugin- 前缀。这里为eslint-plugin-react
plugins: [
'react',
],
rules: {
},
};
注意:支持 ES6 语法并不意味着同时支持新的 ES6 全局变量或类型(比如 Set 等新类型)。对于 ES6 语法,使用 { "parserOptions": { "ecmaVersion": 6 } };对于新的 ES6 全局变量,使用 { "env":{ "es6": true } }。
{ "env": { "es6": true } } 自动启用es6语法,但 { "parserOptions": { "ecmaVersion": 6 } } 不自动启用es6全局变量。
2. 集成到webpack中
需要安装babel-eslint(eslint支持babel), eslint-loader(eslint支持webpack)
cnpm i eslint babel-eslint eslint-loader -D
配置eslintrc.js
{
"parser": "babel-eslint",
}
webpack.config.js
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', {
loader: 'eslint-loader', //先eslint 后babel
options: {
fix: true, // 自动修复eslint
cache: true // 缓存
},
}]
},
...
3. 在代码commit前进行eslint校验
安装pre-commit
cnpm i pre-commit -D
package.json
{
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "eslint .", // 校验所有文件
"fix": "eslint --fix ." // 修复所有文件
},
"pre-commit": [
"fix",
"lint" // 依次执行 npm run fix、 npm run lint 命令
],
}
4. 在vscode中保存修复eslint和快捷键设置
安装eslint扩展

设置与键盘快捷方式设置

eslint设置

快捷键绑定
结合editorconfig自动格式化

.editorconfig 如下
root = true # 根目录的配置文件,编辑器会由当前目录向上查找,如果找到 `roor = true` 的文件,则不再查找
[*] # 匹配所有的文件
indent_style = space # 空格缩进
indent_size = 4 # 缩进空格为4个
max_line_length = 100 # 单行最大长度
end_of_line = lf # 文件换行符是 linux 的 `\n`
charset = utf-8 # 文件编码是 utf-8
trim_trailing_whitespace = true # 不保留行末的空格
insert_final_newline = true # 文件末尾添加一个空行
curly_bracket_next_line = false # 大括号不另起一行
spaces_around_operators = true # 运算符两遍都有空格
indent_brace_style = 1tbs # 条件语句格式是 1tbs
[*.{js,jsx}] # 对所有的 js 文件生效
quote_type = single # 字符串使用单引号
[*.{html,less,css,json}] # 对所有 html, less, css, json 文件生效
quote_type = double # 字符串使用双引号
[package.json] # 对 package.json 生效
indent_size = 2 # 使用2个空格缩进
以上。

浙公网安备 33010602011771号