Eslint
提示
js校验必备,注意eslint只针对js或ts做校验
Eslint 相关文档
从 ESLint 开始,说透我如何在团队项目中基于 Vue 做代码校验
注意node的版本
To use ESLint, you must have Node.js (^12.22.0, ^14.17.0, or >=16.0.0) installed and built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.)
通用方案
安装步骤
npm install --save-dev eslint
touch .eslintrc.js # 或者npx eslint --init
npm init @eslint/config
配置规则
/*
* "off" 或 0 ==> 关闭规则
* "warn" 或 1 ==> 打开的规则作为警告(不影响代码执行)
* "error" 或 2 ==> 规则作为一个错误(代码不能执行,界面报错)
*/
module.exports = {
env: {
browser: true,
es2021: true,
node: true
},
extends: [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended",
],
overrides: [],
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
},
plugins: ["react", "@typescript-eslint"],
/*
* "off" 或 0 ==> 关闭规则
* "warn" 或 1 ==> 打开的规则作为警告(不影响代码执行)
* "error" 或 2 ==> 规则作为一个错误(代码不能执行,界面报错)
*/
rules: {
'react/react-in-jsx-scope': 'off',
'no-console': 'error', // 禁止使用console
'no-unused-vars': 'error',// 禁止定义未使用的变量
'no-debugger': 'error', // 禁止使用debugger
'no-var': 'error', // 要求使用 let 或 const 而不是 var
},
};
Prettier和ESLint冲突问题
如果项目出现规则冲突以后,需要安装以下插件解决冲突,如果未出现冲突,则可以忽略。
安装插件 eslint-plugin-prettier eslint-config-prettier
npm install eslint-plugin-prettier eslint-config-prettier -D
eslint-config-prettier 的作用是关闭eslint中与prettier相互冲突的规则。
eslint-plugin-prettier 的作用是赋予eslint用prettier格式化代码的能力。
安装依赖并修改.eslintrc文件
prettier 添加到 extends的最后
{
"extends": [
"plugin:prettier/recommended"添加到数组的最后一个元素
]
}
.eslintignore
dist/
node_modules/
types/
cache/
!docs/.vitepress
!/.eslintrc.js
!.test
.temp
ESLint在Vue中的使用详解
vue的 lintonsave 配置项
https://cli.vuejs.org/zh/config/#lintonsave
Type: boolean | 'warning' | 'default' | 'error'
Default: 'default'
是否在开发环境下通过 eslint-loader 在每次保存时 lint 代码。这个值会在 @vue/cli-plugin-eslint 被安装之后生效。
设置为 true 或 'warning' 时,eslint-loader 会将 lint 错误输出为编译警告。默认情况下,警告仅仅会被输出到命令行,且不会使得编译失败。
如果你希望让 lint 错误在开发时直接显示在浏览器中,你可以使用 lintOnSave: 'default'。这会强制 eslint-loader 将 lint 错误输出为编译错误,同时也意味着 lint 错误将会导致编译失败。
设置为 error 将会使得 eslint-loader 把 lint 警告也输出为编译错误,这意味着 lint 警告将会导致编译失败。
或者,你也可以通过设置让浏览器 overlay 同时显示警告和错误:
// vue.config.js
module.exports = {
devServer: {
overlay: {
warnings: true,
errors: true
}
}
}
当 lintOnSave 是一个 truthy 的值时,eslint-loader 在开发和生产构建下都会被启用。如果你想要在生产构建时禁用 eslint-loader,你可以用如下配置:
// vue.config.js
module.exports = {
lintOnSave: process.env.NODE_ENV !== 'production'
}
自动化修复
# 代码格式检查
npm run lint
# 代码格式检查并自动修复
npm run lint -- --fix
只能帮我们自动修复格式类的错误,比如多写了几个空格,缩进,单双引号之类的.
如果是逻辑性的错误,比如定义了变量却没使用vscode按保存是修复不了的,需要手动修改
在 Vue 项目中的实践
关于如何在 Vue 中落地代码校验,一般是有 2 种情况:
- 通过 vue-cli 初始化项目的时候已经选择了对应的校验配置
- 对于一个空的 Vue 项目,想接入代码校验
其实这 2 种情况最终的校验的核心配置都是一样的,只是刚开始的时候安装的包有所区别。
下面通过分析 vue-cli 配置的代码校验,来看看它到底做了哪些事情,通过它安装的包以及包的作用,我们就会知道如何在空项目中配置代码校验了。
通过 vue-cli 初始化的项目
如果你的项目最初是通过 vue-cli 新建的,那么在新建的时候会让你选
- 是否支持 eslint;
- 是否开启保存校验;
- 是否开启提交前校验;
如果都开启了话,会安装如下几个包:
- eslint:前面 2 大章节介绍的就是这玩意,ESLint 出品,是代码校验的基础包,且提供了很多内置的 Rules,比如 eslint:recommended 经常被作为项目的 JS 检查规范被引入;
- babel-eslint:一个对 Babel 解析器的包装,使其能够与 ESLint 兼容;
- lint-staged:请看后面 pre-commit 部分;
- @vue/cli-plugin-eslint
- eslint-plugin-vue
下面重点介绍 @vue/cli-plugin-eslint 和 eslint-plugin-vue,说下这 2 个包是干嘛的。
@vue/cli-plugin-eslint 这个包它主要干了 2 件事情:
第一件事
往 package.json 里注册了一个命令:
{
"scripts": {
"lint": "vue-cli-service lint"
}
}
执行这个命令之后,它会去检查和修复部分可以修复的问题。
默认查找的文件是 src 和 tests 目录下所有的 .js,.jsx,.vue 文件,以及项目根目录下所有的 js 文件(比如,也会检查 .eslintrc.js)。
当然你也可以自定义的传入参数和校验文件:
vue-cli-service lint [options] [...files]
支持的参数如下:
- --no-fix: 不会修复 errors 和 warnings;
- --max-errors [limit]:指定导致出现 npm ERR 错误的最大 errors 数量;
第二件事
增加了代码保存触发校验的功能 lintOnSave,这个功能默认是开启的。如果想要关闭这个功能,可以在 vue.config.js 里配置,习惯上只开启 development 环境下的代码保存校验功能:
module.exports = {
lintOnSave: process.env.NODE_ENV === 'development',
}
lintOnSave 参数说明:
- true 或者 warning:开启保存校验,会将 errors 级别的错误在终端中以 WARNING 的形式显示。默认的,WARNING 将不会导致编译失败;
- false:不开启保存校验;
- error:开启保存校验,会将 errors 级别的错误在终端中以 ERROR 的形式出现,会导致编译失败,同时浏览器页面变黑,显示 Failed to compile。
eslint-plugin-vue
eslint-plugin-vue 是对 .vue 文件进行代码校验的插件。
针对这个插件,它提供了这几个扩展
- plugin:vue/base:基础
- plugin:vue/essential:预防错误的(用于 Vue 2.x)
- plugin:vue/recommended:推荐的,最小化任意选择和认知开销(用于 Vue 2.x);
- plugin:vue/strongly-recommended:强烈推荐,提高可读性(用于 Vue 2.x);
- plugin:vue/vue3-essential:(用于 Vue 3.x)
- plugin:vue/vue3-strongly-recommended:(用于 Vue 3.x)
- plugin:vue/vue3-recommended:(用于 Vue 3.x)
各扩展规则列表:vue rules
看到这么一堆的扩展,是不是都不知道选哪个了
代码规范的东西,原则还是得由各自的团队去磨合商议出一套适合大家的规则。不过,如果你用的是 Vue2,我这里可以推荐 2 套 extends 配置:
{
// Vue 官方示例上的配置
extends: ['eslint:recommended', 'plugin:vue/recommended'],
// 或者使用 AlloyTeam 团队那套
extends: ['alloy', 'alloy/vue']
}
配置和插件对应的解析器
如果是 Vue 2.x 项目,配置了 eslint-plugin-vue 插件和 extends 后,template 校验还是会失效,因为不管是 ESLint 默认的解析器 Espree 还是 babel-eslint 都只能解析 JS,无法解析 template 的内容。
而 vue-eslint-parser 只能解析 template 的内容,但是不会解析 JS,因此还需要对解析器做如下配置:
{
parser: 'vue-eslint-parser',
parseOptions: {
parser: 'babel-eslint',
ecmaVersion: 12,
sourceType: 'module'
},
extends: [
'eslint:recommended',
'plugin:vue/recommended'
],
plugins: ['vue']
}
安装Eslint&Prettier相关依赖
pnpm add eslint prettier eslint-config-prettier eslint-plugin-prettier -Dw
安装检测typescript语法及风格依赖
pnpm add @typescript-eslint/eslint-plugin @typescript-eslint/parser -Dw
.eslintrc
"root": true,
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
"prettier/@typescript-eslint" // 禁用TS插件中与 Prettier 冲突的规则
// 之后vue react等其它插件,需要在后面做配置
// prettier/**
// 解决Prettier与插件之间兼容问题
],
"overrides": [],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"rules": {}
}
Vue3+ESLint+Prettier实现保存自动格式化代码
https://blog.csdn.net/qq_44910894/article/details/131012372
配置Eslint
项目搭建完成后,根目录下会自动生成一个.eslintrc.js文件,我们直接来看默认的配置:
module.exports = {
root: true,
env: {
node: true
},
extends: ['plugin:vue/essential', '@vue/prettier'],
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
},
parserOptions: {
parser: '@typescript-eslint/parser'
}
}
这里extends是一个数组,数组第一个成员"plugin:vue/essential"表示的是:引入eslint-plugin-vue插件,并开启essential类别中的一系列规则。
eslint-plugin-vue把所有规则分为四个类别,依次为:base, essential, strongly-recommended, recommended,后面的每个类别都是对前一个类别的拓展。除了这四个类别外,还有两个未归类的规则,所有的类别及规则都可以在这里查看。
这里默认启用的是essential类别里面的规则,我们也可以使用"plugin:vue/strongly-recommended" 或 "plugin:vue/recommend" 启用更多的规则,如果仅仅想启用strongly-recommended和recommend里面的部分规则,可以在.eslintrc.js文件的rules选项中配置。
eslint 补充知识
extends的属性值可以是:
指定配置的字符串(配置文件的路径、可共享配置的名称、eslint:recommended 或 eslint:all) 字符串数组:每个配置继承它前面的配置 可选的配置项如下:
eslint:recommended 启用一些列核心规则 可共享的配置(比如,eslint-config-standard),这是一个npm包,属性值可以省略包名的前缀eslint-config- 插件,是一个 npm 包,属性值可以省略包名的前缀eslint-plugin-,属性值为,plugin:包名/配置名称 指向一个配置文件的相对路径或绝对路径 eslint:all 启用当前安装的eslint版本中所有核心规则,不推荐使用 plugins的属性值是一个字符串列表:
在使用插件之前,你必须安装它 插件名称可以省略eslint-plugin-前缀 eslint规则文档中,带扳手图标的规则就是eslint能够自动修复的规则。而不带该图标的规则,eslint则只能给出错误或警告,需要开发者手动修复。
如何在老项目中加入ESlint
- 在目录中添加.editorconfig、.eslintrc.js、.eslintignore这三个文件
- 在package.json的”devDependencies”中加入ESlint所需要的包
"babel-eslint": "^7.1.1",
"eslint": "^3.19.0",
"eslint-config-standard": "^10.2.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-html": "^3.0.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^5.2.0",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^3.0.1",
- 在bulid/webpack.base.conf.js文件中加入ESlint规则并生效
// 在module的rules中加入
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'), // 不符合Eslint规则时只警告(默认运行出错)
// emitWarning: !config.dev.showEslintErrorsInOverlay
}
},
]
}
- 重新bulid代码运行,完美生效!!!!!!
格式化属性换行 vue/max-attributes-per-line
vue/max-attributes-per-line 强制每行最大的属性数目 分两头
单行的情况下可以接受的数量是可配置的。(默认1)
多行的情况下,每行可接受多少个属性。(默认1)
"vue/max-attributes-per-line": ["error", {
"singleline": 3,
"multiline": {
"max": 1,
"allowFirstLine": false
}
}],
个人设定的是单行每行不能超过3个,多行每行不能超过一个,而且不允许在多行的情况下第一行有属性。 举个栗子
<template>
<MyComponent
lorem="1"
ipsum="2"
dolor="3"
/>
</template>
当时设置allowFirstLine为false,上面代码这样的格式是不允许的。
通常vue项目推荐设置
rules:{
'vue/max-attributes-per-line': [
2,
{
singleline: 10,
multiline: {
max: 1,
allowFirstLine: true // 首行允许属性
}
}
]
}
配置扩展 extends
实际项目中配置规则的时候,不可能团队一条一条的去商议配置,太费精力了。通常的做法是使用业内大家普通使用的、遵循的编码规范;然后通过 extends 去引入这些规范。
extends 配置的时候接受字符串或者数组:
{
extends: [
'eslint:recommended',
'plugin:vue/essential',
'eslint-config-standard', // 可以缩写成 'standard'
'@vue/prettier',
'./node_modules/coding-standard/.eslintrc-es6'
]
}
从上面的配置,可以知道 extends 支持的配置类型可以是以下几种
- eslint 开头的:是 ESLint 官方的扩展;
- plugin 开头的:是插件类型扩展,比如 plugin:vue/essential;
- eslint-config 开头的:来自 npm 包,使用时可以省略前缀 eslint-config-,比如上面的可以直接写成 standard;
- @开头的:扩展和 eslint-config 一样,只是在 npm 包上面加了一层作用域 scope;
- 一个执行配置文件的相对路径或绝对路径;
那有哪些常用的、比较著名扩展可以被 extends 引入呢
- eslint:recommended:ESLint 内置的推荐规则,即 ESLint Rules 列表中打了钩的那些规则;
- eslint:all:ESLint 内置的所有规则;
- eslint-config-standard:standard 的 JS 规范;
- eslint-config-prettier:关闭和 ESLint 中以及其他扩展中有冲突的规则;
- eslint-config-airbnb-base:airbab 的 JS 规范;
- eslint-config-alloy:腾讯 AlloyTeam 前端团队出品,可以很好的针对你项目的技术栈进行配置选择,比如可以选 React、Vue(现已支持 Vue 3.0)、TypeScript 等;
规则等级
规则的校验说明,有 3 个报错等级
• off 或 0:关闭对该规则的校验;
• warn 或 1:启用规则,不满足时抛出警告,且不会退出编译进程;
• error 或 2:启用规则,不满足时抛出错误,且会退出编译进程;
如何知道某个扩展有哪些规则可以配置,以及每个规则具体限制?这里直接给出业内著名且使用比较多的规则列表的快速链接:
• ESLint rules,这整个列表对应 eslint:all,而打钩 ✔️ 的是 eslint:recommenmed; • Prettier rules • standard rules • airbnb rules • AlloyTeam vue rules
规则的优先级
- 如果 extends 配置的是一个数组,那么最终会将所有规则项进行合并,出现冲突的时候,后面的会覆盖前面的;
- 通过 rules 单独配置的规则优先级比 extends 高;
针对个别文件设置新的检查规则
比如 webpack 的中包含了某些运行时的 JS 文件,而这些文件是只跑在浏览器端的,所以需要针对这部分文件进行差异化配置:
overrides: [
{
files: ["lib/**/*.runtime.js", "hot/*.js"],
env: {
es6: false,
browser: true
},
globals: {
Promise: false
},
parserOptions: {
ecmaVersion: 5
}
}
]
快速创建一个eslint配置文件
# 安装 eslint
npm i eslint -D
# 初始化一个配置文件
npx eslint --init
# 可以通过 --ext 来指定具体需要校验的文件:
npx eslint --ext .js,.jsx,.vue src
把校验命令加到 package.json
{
"scripts": {
"lint": "npx eslint --ext .js,.jsx,.vue src",
"lint:fix": "npx eslint --fix --ext .js,.jsx,.vue src",
}
}
过滤一些不需要校验的文件
# 在项目根目录通过创建一个 .eslintignore 文件
public/
src/main.js
除了 .eslintignore 中指定的文件或目录,ESLint 总是忽略 /node_modules/ 和 /bower_components/ 中的文件;
因此对于一些目前解决不了的规则报错,但是如果又急于打包上线,在不影响运行的情况下,我们就可以利用 .eslintignore 文件将其暂时忽略。
eslint常见报错
文件末尾存在空行(eol-last):Too many blank lines at the end of file.Max of 0 allowed
缺少分号(‘semi’: [‘error’,’always’]) :Missing semicolon
函数关键字后面缺少空格 :Missing space before function parentheses
字符串没有使用单引号(’quotes’: [1, ’single’]) :String must use singlequote
缩进错误 : Expected indentation of 2 spaces but found 4
没有使用全等(eqeqeq) : Expected ’ === ’ and instaed saw ‘==’
导入组件却没有使用 : ‘seller’ is defined but never used
new了一个对象却没有赋值给某个常量(可以在该实例前添加此代码/eslint-disable
no-new/忽略ESLint的检查): Do not user’new’ for side effects
超过一行空白行(no-multiple-empty-lines):More than 1 blank line not allowed
注释符 // 后面缩进错误(lines-around-comment): Expected space or tab after ‘//’ in comment
模块导入没有放在顶部:Import in body of module; reorder to top
前面缺少空格:Missing space before
已定义但是没有使用:‘scope’ is defined but never used
"no-alert": 0,//禁止使用alert confirm prompt
"no-array-constructor": 2,//禁止使用数组构造器
"no-bitwise": 0,//禁止使用按位运算符
"no-caller": 1,//禁止使用arguments.caller或arguments.callee
"no-catch-shadow": 2,//禁止catch子句参数与外部作用域变量同名
"no-class-assign": 2,//禁止给类赋值
"no-cond-assign": 2,//禁止在条件表达式中使用赋值语句
"no-console": 2,//禁止使用console
"no-const-assign": 2,//禁止修改const声明的变量
"no-constant-condition": 2,//禁止在条件中使用常量表达式 if(true) if(1)
"no-continue": 0,//禁止使用continue
"no-control-regex": 2,//禁止在正则表达式中使用控制字符
"no-debugger": 2,//禁止使用debugger
"no-delete-var": 2,//不能对var声明的变量使用delete操作符
"no-div-regex": 1,//不能使用看起来像除法的正则表达式/=foo/
"no-dupe-keys": 2,//在创建对象字面量时不允许键重复 {a:1,a:1}
"no-dupe-args": 2,//函数参数不能重复
"no-duplicate-case": 2,//switch中的case标签不能重复
"no-else-return": 2,//如果if语句里面有return,后面不能跟else语句
"no-empty": 2,//块语句中的内容不能为空
"no-empty-character-class": 2,//正则表达式中的[]内容不能为空
"no-empty-label": 2,//禁止使用空label
"no-eq-null": 2,//禁止对null使用==或!=运算符
"no-eval": 1,//禁止使用eval
"no-ex-assign": 2,//禁止给catch语句中的异常参数赋值
"no-extend-native": 2,//禁止扩展native对象
"no-extra-bind": 2,//禁止不必要的函数绑定
"no-extra-boolean-cast": 2,//禁止不必要的bool转换
"no-extra-parens": 2,//禁止非必要的括号
"no-extra-semi": 2,//禁止多余的冒号
"no-fallthrough": 1,//禁止switch穿透
"no-floating-decimal": 2,//禁止省略浮点数中的0 .5 3.
"no-func-assign": 2,//禁止重复的函数声明
"no-implicit-coercion": 1,//禁止隐式转换
"no-implied-eval": 2,//禁止使用隐式eval
"no-inline-comments": 0,//禁止行内备注
"no-inner-declarations": [2, "functions"],//禁止在块语句中使用声明(变量或函数)
"no-invalid-regexp": 2,//禁止无效的正则表达式
"no-invalid-this": 2,//禁止无效的this,只能用在构造器,类,对象字面量
"no-irregular-whitespace": 2,//不能有不规则的空格
"no-iterator": 2,//禁止使用__iterator__ 属性
"no-label-var": 2,//label名不能与var声明的变量名相同
"no-labels": 2,//禁止标签声明
"no-lone-blocks": 2,//禁止不必要的嵌套块
"no-lonely-if": 2,//禁止else语句内只有if语句
"no-loop-func": 1,//禁止在循环中使用函数(如果没有引用外部变量不形成闭包就可以)
"no-mixed-requires": [0, false],//声明时不能混用声明类型
"no-mixed-spaces-and-tabs": [2, false],//禁止混用tab和空格
"linebreak-style": [0, "windows"],//换行风格
"no-multi-spaces": 1,//不能用多余的空格
"no-multi-str": 2,//字符串不能用\换行
"no-multiple-empty-lines": [1, {"max": 2}],//空行最多不能超过2行
"no-native-reassign": 2,//不能重写native对象
"no-negated-in-lhs": 2,//in 操作符的左边不能有!
"no-nested-ternary": 0,//禁止使用嵌套的三目运算
"no-new": 1,//禁止在使用new构造一个实例后不赋值
"no-new-func": 1,//禁止使用new Function
"no-new-object": 2,//禁止使用new Object()
"no-new-require": 2,//禁止使用new require
"no-new-wrappers": 2,//禁止使用new创建包装实例,new String new Boolean new Number
"no-obj-calls": 2,//不能调用内置的全局对象,比如Math() JSON()
"no-octal": 2,//禁止使用八进制数字
"no-octal-escape": 2,//禁止使用八进制转义序列
"no-param-reassign": 2,//禁止给参数重新赋值
"no-path-concat": 0,//node中不能使用__dirname或__filename做路径拼接
"no-plusplus": 0,//禁止使用++,--
"no-process-env": 0,//禁止使用process.env
"no-process-exit": 0,//禁止使用process.exit()
"no-proto": 2,//禁止使用__proto__属性
"no-redeclare": 2,//禁止重复声明变量
"no-regex-spaces": 2,//禁止在正则表达式字面量中使用多个空格 /foo bar/
"no-restricted-modules": 0,//如果禁用了指定模块,使用就会报错
"no-return-assign": 1,//return 语句中不能有赋值表达式
"no-script-url": 0,//禁止使用javascript:void(0)
"no-self-compare": 2,//不能比较自身
"no-sequences": 0,//禁止使用逗号运算符
"no-shadow": 2,//外部作用域中的变量不能与它所包含的作用域中的变量或参数同名
"no-shadow-restricted-names": 2,//严格模式中规定的限制标识符不能作为声明时的变量名使用
"no-spaced-func": 2,//函数调用时 函数名与()之间不能有空格
"no-sparse-arrays": 2,//禁止稀疏数组, [1,,2]
"no-sync": 0,//nodejs 禁止同步方法
"no-ternary": 0,//禁止使用三目运算符
"no-trailing-spaces": 1,//一行结束后面不要有空格
"no-this-before-super": 0,//在调用super()之前不能使用this或super
"no-throw-literal": 2,//禁止抛出字面量错误 throw "error";
"no-undef": 1,//不能有未定义的变量
"no-undef-init": 2,//变量初始化时不能直接给它赋值为undefined
"no-undefined": 2,//不能使用undefined
"no-unexpected-multiline": 2,//避免多行表达式
"no-underscore-dangle": 1,//标识符不能以_开头或结尾
"no-unneeded-ternary": 2,//禁止不必要的嵌套 var isYes = answer === 1 ? true : false;
"no-unreachable": 2,//不能有无法执行的代码
"no-unused-expressions": 2,//禁止无用的表达式
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}],//不能有声明后未被使用的变量或参数
"no-use-before-define": 2,//未定义前不能使用
"no-useless-call": 2,//禁止不必要的call和apply
"no-void": 2,//禁用void操作符
"no-var": 0,//禁用var,用let和const代替
"no-warning-comments": [1, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],//不能有警告备注
"no-with": 2,//禁用with
"array-bracket-spacing": [2, "never"],//是否允许非空数组里面有多余的空格
"arrow-parens": 0,//箭头函数用小括号括起来
"arrow-spacing": 0,//=>的前/后括号
"accessor-pairs": 0,//在对象中使用getter/setter
"block-scoped-var": 0,//块语句中使用var
"brace-style": [1, "1tbs"],//大括号风格
"callback-return": 1,//避免多次调用回调什么的
"camelcase": 2,//强制驼峰法命名
"comma-dangle": [2, "never"],//对象字面量项尾不能有逗号
"comma-spacing": 0,//逗号前后的空格
"comma-style": [2, "last"],//逗号风格,换行时在行首还是行尾
"complexity": [0, 11],//循环复杂度
"computed-property-spacing": [0, "never"],//是否允许计算后的键名什么的
"consistent-return": 0,//return 后面是否允许省略
"consistent-this": [2, "that"],//this别名
"constructor-super": 0,//非派生类不能调用super,派生类必须调用super
"curly": [2, "all"],//必须使用 if(){} 中的{}
"default-case": 2,//switch语句最后必须有default
"dot-location": 0,//对象访问符的位置,换行的时候在行首还是行尾
"dot-notation": [0, { "allowKeywords": true }],//避免不必要的方括号
"eol-last": 0,//文件以单一的换行符结束
"eqeqeq": 2,//必须使用全等
"func-names": 0,//函数表达式必须有名字
"func-style": [0, "declaration"],//函数风格,规定只能使用函数声明/函数表达式
"generator-star-spacing": 0,//生成器函数*的前后空格
"guard-for-in": 0,//for in循环要用if语句过滤
"handle-callback-err": 0,//nodejs 处理错误
"id-length": 0,//变量名长度
"indent": [2, 4],//缩进风格
"init-declarations": 0,//声明时必须赋初值
"key-spacing": [0, { "beforeColon": false, "afterColon": true }],//对象字面量中冒号的前后空格
"lines-around-comment": 0,//行前/行后备注
"max-depth": [0, 4],//嵌套块深度
"max-len": [0, 80, 4],//字符串最大长度
"max-nested-callbacks": [0, 2],//回调嵌套深度
"max-params": [0, 3],//函数最多只能有3个参数
"max-statements": [0, 10],//函数内最多有几个声明
"new-cap": 2,//函数名首行大写必须使用new方式调用,首行小写必须用不带new方式调用
"new-parens": 2,//new时必须加小括号
"newline-after-var": 2,//变量声明后是否需要空一行
"object-curly-spacing": [0, "never"],//大括号内是否允许不必要的空格
"object-shorthand": 0,//强制对象字面量缩写语法
"one-var": 1,//连续声明
"operator-assignment": [0, "always"],//赋值运算符 += -=什么的
"operator-linebreak": [2, "after"],//换行时运算符在行尾还是行首
"padded-blocks": 0,//块语句内行首行尾是否要空行
"prefer-const": 0,//首选const
"prefer-spread": 0,//首选展开运算
"prefer-reflect": 0,//首选Reflect的方法
"quotes": [1, "single"],//引号类型 `` "" ''
"quote-props":[2, "always"],//对象字面量中的属性名是否强制双引号
"radix": 2,//parseInt必须指定第二个参数
"id-match": 0,//命名检测
"require-yield": 0,//生成器函数必须有yield
"semi": [2, "always"],//语句强制分号结尾
"semi-spacing": [0, {"before": false, "after": true}],//分号前后空格
"sort-vars": 0,//变量声明时排序
"space-after-keywords": [0, "always"],//关键字后面是否要空一格
"space-before-blocks": [0, "always"],//不以新行开始的块{前面要不要有空格
"space-before-function-paren": [0, "always"],//函数定义时括号前面要不要有空格
"space-in-parens": [0, "never"],//小括号里面要不要有空格
"space-infix-ops": 0,//中缀操作符周围要不要有空格
"space-return-throw-case": 2,//return throw case后面要不要加空格
"space-unary-ops": [0, { "words": true, "nonwords": false }],//一元运算符的前/后要不要加空格
"spaced-comment": 0,//注释风格要不要有空格什么的
"strict": 2,//使用严格模式
"use-isnan": 2,//禁止比较时使用NaN,只能用isNaN()
"valid-jsdoc": 0,//jsdoc规则
"valid-typeof": 2,//必须使用合法的typeof的值
"vars-on-top": 2,//var必须放在作用域顶部
"wrap-iife": [2, "inside"],//立即执行函数表达式的小括号风格
"wrap-regex": 0,//正则表达式字面量用小括号包起来
"yoda": [2, "never"]//禁止尤达条件
module.exports = { // 此项是用来告诉eslint找当前配置文件不能往父级查找
root: true,
// 此项是用来指定eslint解析器的,解析器必须符合规则,babel-eslint解析器是对babel解析器的包装使其与ESLint解析
parser: 'babel-eslint',
// 此项是用来指定javaScript语言类型和风格,sourceType用来指定js导入的方式,默认是script,此处设置为module,指某块导入方式
parserOptions: {
sourceType: 'module'
},
// 此项指定环境的全局变量,下面的配置指定为浏览器环境
env: {
browser: true,
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
// 此项是用来配置标准的js风格,就是说写代码的时候要规范的写,如果你使用vs-code我觉得应该可以避免出错
extends: 'standard', // required to lint *.vue files
// 此项是用来提供插件的,插件名称省略了eslint-plugin-,下面这个配置是用来规范html的
plugins: [
'html'
], // add your custom rules here
// 下面这些rules是用来设置从插件来的规范代码的规则,使用必须去掉前缀eslint-plugin-
// 主要有如下的设置规则,可以设置字符串也可以设置数字,两者效果一致
// "off" -> 0 关闭规则
// "warn" -> 1 开启警告规则
// "error" -> 2 开启错误规则
// 了解了上面这些,下面这些代码相信也看的明白了
rules: {
// allow async-await
'generator-star-spacing': 'off',
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
// js语句结尾必须使用分号
'semi': ['off', 'always'],
// 三等号
'eqeqeq': 0,
// 强制在注释中 // 或 /* 使用一致的空格
'spaced-comment': 0,
// 关键字后面使用一致的空格
'keyword-spacing': 0,
// 强制在 function的左括号之前使用一致的空格
'space-before-function-paren': 0,
// 引号类型
'quotes': [0, 'single'],
// 禁止出现未使用过的变量
// 'no-unused-vars': 0,
// 要求或禁止末尾逗号
'comma-dangle': 0
}
}
使用 eslint 自动调整 import 代码顺序
提供 sort-imports 能力的插件有好几个,试了一下,eslint-plugin-simple-import-sort 最靠谱。
yarn add -D eslint-plugin-simple-import-sort
配置 在 .eslintrc 中分别加入:
{
"plugins": [
"simple-import-sort"
],
"rules": {
"simple-import-sort/imports": "error",
"simple-import-sort/exports": "error"
}
}
体验 执行 eslint --fix src/**,完美。
React相关
React 编译模式配置
如果 React 使用的是新的编译模式(无需手动导入 React),需要在 extends 中加入 plugin:react/jsx-runtime。
{
"extends": [
"plugin:react/jsx-runtime"
]
}
同时 tsconfig 文件中的 “jsx”: “react-jsx”
也是对应的新模式。
React 属性自动排序规则配置
安装依赖:
ni -D eslint-plugin-react
确保 eslint 配置文件中 extends 的部分存在 plugin:react/recommended
。
React 组件的属性可以借助 eslint 的能力来进行自动排序,在配置文件的 rule 中打开即可。
{
"rules": {
"react/jsx-sort-props": [
"error",
{
"callbacksLast": true
}
]
}
}