ESlint使用心得

672 阅读5分钟

前言

  • ESLint 是一个开源的 JavaScript 代码检查工具
  • JavaScript 是一个动态的弱类型语言,在开发中比较容易出错。因为没有编译程序,为了寻找 JavaScript 代码错误通常需要在执行过程中不断调试。像 ESLint 这样的可以让程序员在编码的过程中发现问题而不是在执行的过程中
  • ESLint 的初衷是为了让程序员可以创建自己的检测规则。ESLint 的所有规则都被设计成可插入的
  • ESLint 使用 Node.js 编写

eslint配置文件

  • JavaScript - 使用 .eslintrc.js 然后输出一个配置对象。
  • YAML - 使用 .eslintrc.yaml 或 .eslintrc.yml 去定义配置的结构。
  • JSON - 使用 .eslintrc.json 去定义配置的结构,ESLint 的 JSON 文件允许 JavaScript 风格的注释。
  • package.json - 在 package.json 里创建一个 eslintConfig属性,在那里定义你的配置。

文件优先级

同级目录,只会执行优先级高的文件规则

  1. .eslintrc.js
  2. .eslintrc.yaml
  3. .eslintrc.yml
  4. .eslintrc.json
  5. package.json

非同级目录,即层叠配置

优先匹配同级目录的规则,会覆盖父级的规则以及更远一直到根目录的规则

限制到特定的项目

一旦发现配置文件中有 {"root": true},它就会停止在父级目录中寻找

全局配置

当项目内不存在规则文件,退回到 ~/.eslintrc 中自定义的默认配置。

使用"eslint:recommended"

eslint --init 命令可以创建一个配置,以下是.eslintrc.js文件的示例

module.exports = {
	//继承: 规则:核心规则
    "extends": "eslint:recommended",
    //自定义规则
    "rules": {
        // enable additional rules
        "indent": ["error", 4],
        "linebreak-style": ["error", "unix"],
        "quotes": ["error", "double"],
        "semi": ["error", "always"],

        // override default options for rules from base configurations
        "comma-dangle": ["error", "always"],
        "no-cond-assign": ["error", "always"],

        // disable rules from base configurations
        "no-console": "off",
    }
}

使用<可共享的配置>

可共享的配置 是一个 npm 包,它输出一个配置对象。要确保这个包安装在 ESLint 能请求到的目录下。

extends 属性值可以省略包名的前缀 eslint-config-。

eslint --init 命令可以创建一个配置,这样你就可以扩展一个流行的风格指南(比如,eslint-config-standard)。

YAML 格式的一个配置文件的例子:

extends: standard
rules:
  comma-dangle:
    - error
    - always
  no-empty: warn

使用Plugins

插件 是一个 npm 包,通常输出规则。一些插件也可以输出一个或多个命名的 配置。要确保这个包安装在 ESLint 能请求到的目录下。

plugins 属性值 可以省略包名的前缀 eslint-plugin-。

extends 属性值可以由以下组成:

plugin: 包名 (省略了前缀,比如,react) / 配置名称 (比如 recommended) JSON 格式的一个配置文件的例子:

{
    "plugins": [
        "react"
    ],
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended"
    ],
    "rules": {
       "no-set-state": "off"
    }
}

使用Glob Patterns(v4.1.0+)

Glob 模式覆盖只能在配置文件 (.eslintrc.* 或 package.json) 中进行配置。

覆盖块也可以指定从匹配中排除的模式。如果一个文件匹配了任何一个排除模式,该配置将不再被应用。

eg:

{
  "rules": {
    "quotes": ["error", "double"]
  },

  "overrides": [
    {
      "files": ["bin/*.js", "lib/*.js"],
      "excludedFiles": "*.test.js",
      "rules": {
        "quotes": ["error", "single"]
      }
    }
  ]
}

使用.eslintignore

ESLint 去忽略特定的文件和目录

.eslintignore 文件是一个纯文本文件,其中的每一行都是一个 glob 模式表明哪些路径应该忽略检测。例如,以下将忽略所有的 JavaScript 文件:

**/*.js

Globs 匹配特性:

  • 以 # 开头的行被当作注释,不影响忽略模式。
  • 路径是相对于 .eslintignore 的位置或当前工作目录。通过 --ignore-pattern command 传递的路径也是如此。
  • 忽略模式同 .gitignore 规范
  • 以 ! 开头的行是否定模式,它将会重新包含一个之前被忽略的模式。
  • 忽略模式依照 .gitignore 规范.

安装VScode插件

  • ESLint(代码检查)
  • Prettier - Code formatter(代码格式化) 这样可以让编码过程更自动化

vscode中setting.json中配置

{
 // vscode默认启用了根据文件类型自动设置tabsize的选项
 "editor.detectIndentation": false,
 // 重新设定tabsize
 "editor.tabSize": 2,
 // #每次保存的时候自动格式化 
 "editor.formatOnSave": true,
 // #每次保存的时候将代码按eslint格式进行修复
 "eslint.autoFixOnSave": true,
 // 添加 vue 支持
 "eslint.validate": [
  "javascript",
  "javascriptreact",
  {
   "language": "html",
   "autoFix": true
  },
  {
   "language": "vue",
   "autoFix": true
  }
 ],
 // #让prettier使用eslint的代码格式进行校验 
 "prettier.eslintIntegration": true,
 // #去掉代码结尾的分号 
 "prettier.semi": false,
 // #使用单引号替代双引号 
 "prettier.singleQuote": false,
 // #让函数(名)和后面的括号之间加个空格
 "javascript.format.insertSpaceBeforeFunctionParenthesis": false,
 // #这个按用户自身习惯选择 
 "vetur.format.defaultFormatter.html": "js-beautify-html",
 // #让vue中的js按编辑器自带的ts格式进行格式化 
 "vetur.format.defaultFormatter.js": "vscode-typescript",
 "vetur.format.defaultFormatterOptions": {
  "js-beautify-html": {
   "wrap_attributes": "force-aligned"
   // #vue组件中html代码格式化样式
  }
 },
 // 格式化stylus, 需安装Manta's Stylus Supremacy插件
 "stylusSupremacy.insertColons": false, // 是否插入冒号
 "stylusSupremacy.insertSemicolons": false, // 是否插入分号
 "stylusSupremacy.insertBraces": false, // 是否插入大括号
 "stylusSupremacy.insertNewLineAroundImports": false, // import之后是否换行
 "stylusSupremacy.insertNewLineAroundBlocks": false,
 "window.zoomLevel": 0 // 两个选择器中是否换行
}

自定义eslint规则

根目录下新建.eslintrc.js,前提是项目已安装eslint和相关eslint依赖

module.exports={
	'root':true,
    'env':{
    	node:true
    },
    'extends':[
    	'plugin:vue/essential',
        '@vue/standard
    ],
    rules:{
    	'comma-sapcing':[2,{
        	'before':false,
            'after':true
        }],
        'indent':[2,4],//缩进
        'quotes':[2,'single'],//引号,单引号
        'no-extra-semi':2,
        'semi':[2,'always'],
        'space-before-function-paren':[2,'never']//禁止函数圆括号之前有一个空格
        'arrow-parens':[2,'as-needed'],
        'quote-props':[2,'consistent'],
        'comma-dangle':['error','only-multiline'],
        'object-curly-spacing':['error','never'],
        'no-param-reassign':0,
        'no-restricted-globals':0,
        'eol-last'0,//结尾换行
        'vue/html-indent':['error',4,{
        	'attribute'1,
            'closeBracket':0,
            'alignAttributesVertically':true,
            'ignores'[]
        }],
        'vue/mustache-interpolation-spacing':[2,'always'|'never'],
        'vue/v-bind-style':[2,'shorthand'],
        'vue/script-indent':['error',4],
        'no-console':process.env.NODE_ENV==='production'?'error':'off',
        'no-debugger':process.env.NODE_ENV==='production'?'error':'off',
    },
    'parserOptions':{
    	parser:'babel-eslint'
    }
}

结语

更多规则设置:eslint.bootcss.com/docs/rules/

其他优秀回答:www.jianshu.com/p/733d7c356…