ESLint comprehensive analysis

Preface

ESLint is a code development tool that can coordinate and unify the coding style of the team. Developers who are new to ESLint will feel frustrated when using it. The essence of ESLint is to provide specifications and formulate rules to limit developers' coding. For example, ESLint In such a rule defined in, code indentation can only use 2 spaces, if you use 4 spaces, an error will be reported.

As a developer, it is uncomfortable not to write code as you want, but once the adaptation period has passed, the code written in the future will become more beautiful and easier to read.

In a multi-person collaborative team, to complete a large project together, ESLint is an indispensable development tool. This article will interpret ESLint from three directions.

  • Understand the meaning of each attribute from the basic configuration of ESLint
  • How to automatically identify and fix ESLint errors with the help of vscode editor to improve development efficiency
  • Other application scenarios of ESLint

Basic configuration

Build the simplest ESLint project

1. Create a new folder and enter the directory to execute and npm init -ycreate a new project.

2. Perform the npm i eslint -Dinstallation of ESLint dependencies.

3. Create a .eslintignorefile in the project root directory , set the files that need to be ignored by ESLint, and fill in the following code in the file. The files in the following marked directories will not be checked by ESLint.

build
dist
src/assets
public
node_modules

4. Create a .eslintrc.jsfile in the project root directory . This file is the core configuration file of ESLint. All code constraint rules can be written in this file.

module.exports = {
  root: true,
  env: {
    node: true,
    browser: true,
    es6: true
  },
  parser:"Espree",
  parserOptions:{
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
        }
  },
  globals:{
    "data1":"writable",
    "data2":"readonly"  
  },
  extends: [
    'eslint:recommended'
  ],
  rules: {
    "indent": ["error", 2], //代码缩进2个空格
    'quotes': ['error', 'single'], // 字符串强制使用单引号
    'eqeqeq': ['error', 'always', { null: 'ignore' }], //比较时强制使用 === 或者 !==,但对null作比较时可以不用全等
  }
}

The above configuration attributes are the most commonly used configuration items, which are explained one by one below.

root

By default, ESLint will always search for the configuration file up to the root directory.Once it is found that the configuration file is configured with the root parameter and is true at a certain level, ESLint will stop searching for the upper level, and its scope will be determined.

env

 env: {
    node: true,
    browser: true,
    es6: true
  },

Specify the environment in which the script is allowed to run. For example, if the es6 configuration above is false, if the let and const keywords appear in the code, ESLint will report an error. Another example is to set the browser to true, which means that the script is allowed to run in the browser environment. There will be no error if the global variable window appears in the code. If you set browser to false, an error will be reported if the global variable window appears in the code.

parser和parserOptions

  parser:"Espree",
  parserOptions:{
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
        }
  }

ESLint is a program for grammar verification. If the code is passed to it for verification, the premise is that it can correctly identify the code. For example, writing a piece of jsx code without any configuration and submitting it to ESLint for verification will definitely report an error, because of these Code It found that it could not run illegal code.

parser specifies the engine of a code parser, and lets it detect whether the code is legal or not. The default option is Espree. If you want to change to a parser, for example babel-eslint, you need to npm i babel-eslint -Dinstall it first , and then fill in the above configuration file parser:"babel-eslint".

ParserOptions is usually used in conjunction with parser, it is used to specify the specific strategy of how to parse the code. There are the following properties:

  • ecmaVersion: Specify the version of the js code that is allowed to be written, such as ecmaVersion is set to 5. If a large number of es6 grammars appear in your code, the parser will report an error and not recognize it.
  • sourceType: There are two options, namely "module" and "script". If you don't set it to module here, then the code cannot appear similar to export default or module.exports module export export syntax.
  • ecmaFeatures: When the jsx option is set to true under it, the jsx code can be written in the code. It should be pointed out here that supporting jsx does not mean supporting react. How to make the react code successfully pass the verification of ESLint will be discussed later. in addition, it can also add a property below impliedStrict:truewhether to turn strict mode globally.

extends

 extends: [
    'eslint:recommended'
 ]

Inherit the configuration rules written by others. For example, it 'eslint:recommended'is the official recommended default rule. In this rule, if a variable is defined and not used, an error will be reported. For detailed configuration details, please go to the ESLint official website.

In addition to the officially recommended rules, we can also use the rules published by others on npm, such as the rules published by airbnb.

  • npm install -D eslint-config-airbnb-base eslint-plugin-import Install dependencies
  • In .eslintrc.jsthe array extends the field plus one
 extends: [
      'eslint:recommended',
      'airbnb-base'
 ],

The above configuration methods are eslint-config-airbnb-baseexplained in detail on the githup homepage. If you want to use other configuration rules, you can also search on githup.

rules

Rules are our custom rules, and its priority is the highest. For example, we have inherited the third-party rules in extends, but we are not satisfied with some rules, we can redefine and override the original rules in rules.

 rules: {
    "indent": ["error", 2], //代码缩进2个空格
    'quotes': ['error', 'single'], // 字符串强制使用单引号
    'eqeqeq': ['error', 'always', { null: 'ignore' }], //比较时强制使用 === 或者 !==,但对null作比较时可以不用全等
  }

Which rules are represented by the attribute names under the rules object. The first value of the array corresponds to the processing method that violates the rule. The values ​​that can be filled are as follows:

  • off or 0: do not verify the rule (if you want to turn off ESLint's verification of a rule directly, you can fill in off)
  • warn or 1: Validate rules but only issue warnings
  • error or 2: An error is reported if the verification rule is found to be inconsistent

There is a rule defined in the above rules "indent": ["error", 2]. indentThe number of spaces for code indentation is specified. The first value of the array errormeans that if it is violated, an error will be reported directly. The other values ​​of the array (there may be multiple values) are passed parameters. For example, the above indentonly allows code indentation Enter two spaces, otherwise ESLint will report an error.

There are thousands of ESLint rules, you can go to the official website to check if you don't know, but the commonly used ones are as follows:

indent: 代码缩进
no-mixed-spaces-and-tabs: 代码缩进不能混用空格和tab。
no-mixed-spaces-and-tabs: 代码缩进不能混用空格和tab。
camelcase: 变量和函数名必须遵循驼峰命名法。
quotes: 字符串使用什么类型的引号
curly: 在 if,else if,else或 while 的代码块中,即使只有一行代码,也要用写在{} 中。
eqeqeq: 比较用 === 或 !==。
no-cond-assign: 不允许在 if 中使用赋值操作。
no-undef: 变量和函数在使用前必须先声明。全局变量或函数除外。
no-unused-vars:变量定义后一定要使用。
no-alert: 禁止使用 alert,confirm 和 prompt。
max-params: 函数允许最多有几个参数。默认是3个。
max-statements: 函数允许最多有几条语句。
max-depth:代码块中默认嵌套深度

plugins

Configuration of plugins which are plug-ins, plug-ins are required to install npm by the role of plug-ins is to supplement the rules, for example, 'eslint:recommended'there is no rule that contains related react, Then you configure it so that ESLint compatible react syntax.

  • npm install eslint-plugin-react --save-devInstallation dependencies
  • Join in extends "plugin:react/recommended"
"extends": [
    "eslint:recommended",
    "plugin:react/recommended"
]
  • Join in the plugin field"react"
"plugins": [
    "react"
 ]
  • Open rule
 "rules": {
    "react/jsx-uses-react": "error",
    "react/jsx-uses-vars": "error",
  }

Thus ESLint will be able to react correctly identify the code and according to eslint-plugin-reactthe rules provided to check the syntax error. Above configuration are eslint-plugin-reacton githup home page written in great detail.

For another example, configure ESLint's support for ts syntax

  • npm i -D typescript @typescript-eslint/parser @typescript-eslint/eslint-pluginInstallation dependency
    Why install @typescript-eslint/parser, because ESLint uses Espree for grammar parsing by default, it cannot recognize some grammars of ts, so we need to install typescript-eslint-parser, replace the default parser, and install typescript at the same time.

  • Configuration file plus the following configuration

{
  "parser": "@typescript-eslint/parser",
  "extends": ["eslint:recommended","plugin:@typescript-eslint/recommended"],
  "plugins": ["@typescript-eslint"],
  "rules": {
    "@typescript-eslint/rule-name": "error"
  }
}

The above configuration methods are @typescript-eslint/eslint-plugindescribed in detail on the main page of the plugin.

If you want to configure vue, you can search directly eslint-plugin-vue, and the official website also has a corresponding configuration method.

globals

globals used to define a global variable, the configuration using the following method in each file can not be defined data1and data2used directly. If not specified directly, ESLint detected variable is not defined it will be given.

globals:{
    "data1":"writable",
    "data2":"readonly"  
}

The variable set by writable can be assigned, while the variable set by readonly can only be read and cannot be modified.

So far, the content of the configuration is finished.

Use comments to ignore ESLint checks

If you want to disable ESLint syntax verification for a single js file, but the entire project still retains the verification rules, you can add a line of comments to the head of the file. ESLint will skip the following comments when it encounters this comment.

/* eslint-disable */

If you want to avoid a certain inspection rule in a certain block of code, you can add a line of comment above the code. It no-consolerefers to the prohibition of the console.logstatement. If you want to avoid a certain inspection, no-consolereplace it with the corresponding rule name.

/* eslint-disable no-console */
 function test(){
   console.log(123);
 }

Perform ESLint detection

After talking so much about the above configuration, we still have to execute ESLint in the end to let it detect whether the code we wrote meets the rules of the above configuration.

For example, create a src/main.jsfile under the current project and write a piece of js code in it.

Open the project root directory and start the command line tool to execute. npx eslint ./src/**/*.jsESLint will go to the src root directory to find all files ending with js, and then check the syntax of the code one by one according to the rules configured above.

vscode assistance

Use the above command line tool to detect errors ESLint it is inefficient, we can make use of vscode by some configuration editor when writing code in real time broke ESLint error, and press ctrl+scan automatically fix errors when saving codes, thus greatly Improved development efficiency.

vscode itself is an editor, the default is to not do ESLint grammar detection by adding plug-ins to extend it, vscode have the ability to read the project .eslintrc.jsconfiguration, and to verify the syntax for writing code in accordance with the rules configuration. The specific configuration steps are as follows.

  • Search ESLint install plugin in vscode
    Insert picture description here

  • Find the setting.json file. Keyboard shortcuts ctrl +shift + p(applicable to windows users) and enter open settings.
    Insert picture description here

  • Add the code to draw the red frame
    Insert picture description here

The ESLint version v2.1.13 currently installed by the author, the configuration method only needs to add the code of the red box above. The red box code is copied directly from the ESLint plug-in document, and you can see it in the lower right corner of the third figure above. To.

If you find that the configuration does not take effect, it is likely that the ESLint version is inconsistent.You need to open the ESLint plugin document in vscode, which will contain detailed configuration instructions.

After the above configuration, the keyboard by pressing ctrl + s, installed ESLint extension vscode automatically formatting code to comply with .eslintrc.jsthe rules defined under the file, do not have to go to every one of them fix the code format.

But it needs to be pointed out here that vscode can only help us automatically repair format errors, such as writing a few more spaces, indentation, single and double quotation marks, etc. If it is a logical error, such as defining a variable but not Using vscode to press save cannot be repaired and needs to be modified manually.

Other scenes

How to integrate ESLint in webpack

  • npm i eslint eslint-loader -D Installation dependencies
  • In webpack.config.jsadding the following configuration
module: {
  rules: [
    {
        test: /\.js$/,
        exclude: /node_modules/, 
        loader: 'eslint-loader',
        options: {
          fix: true // 自动修复某些eslint问题
        }
    }
  ]
}
  • Created in the project root directory .eslintrc.jsand .eslintignoreconfiguration files, and fill your own configuration

If webpack integrated babel, eslint-loaderconfiguration written babel-loaderafter its execution order is from bottom to top.

module: {
  rules: [
    {
      test: /\.js$/,
      exclude: /node_modules/,
      use: [
        {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        }, 
        {
          loader: 'eslint-loader',
          options: {
            fix: true,
          },
        },
      ],
    },
  ],
},

git integrate ESLint

git itself has a hook mechanism, we can trigger ESLint syntax check before git commit through the following configuration.

  • npm install eslint -DInstallation dependencies

  • Created in the project root directory .eslintrc.jsand .eslintignoreconfiguration files, and fill your own configuration

  • npm install pre-commit -D
    After the installation is complete, .git/hooksthere will be an extra pre-commitfile in it. It will store the command line code that will be executed before the git submission.

  • Register the command line code. Add the following code in the package.json file.

{
   "scripts": {
         "eslint": "npx eslint ./src/**/*.js ./src/**/*.ts ./src/**/*.vue"
  	},
   "pre-commit": [
       "eslint"
   ]
}

After the above configuration, the npm run eslintcommand will be executed before git submission , and then ESLint will detect the syntax of all js, ts and vue files under src. If an error is found, the submission will be blocked.

Guess you like

Origin blog.csdn.net/brokenkay/article/details/111106266
Recommended